Can I access a variable (not array) in PHP using index 0 as if it were an array?

Asked

Viewed 198 times

3

The case is this, I have a function that if something happens it creates a array with n numbers ($x[n]) and if another happens it stores in a common variable with the same name ($x).

I know I can instead of storing things in one common variable ($x), could store in a array 0-rated ($x[0]), but while writing the code I came across this doubt and I thought it would be interesting to share this doubt here.

Below is an example:

if (!isset($_POST['x']))
{
    $x = 1;
}
else
{
    for ($i = 0; $i < 10; $i++)
    {
        $x[$i] = $i;
    }
}
echo $x[0]; // Se $_POST['x'] não existir, o número 1 será printado?

This block of code is just an example, I did not use this logic in my program, as I said was just a question that came to me when doing something similar.

Then someone would know to answer that question and if the answer is negative, why it doesn’t work?

  • Enter the code to show how you’re doing. It might be easier to visualize your intention and come up with a solution. Put the generation of array or scalar variable and how it is consuming it. In a general way the answer is not only arrays - of all types, including strings - have index. This does not mean that it cannot be done otherwise.

  • The code is not necessary because I didn’t use it. It was just a question I had while developing, but I will edit with an example.

2 answers

4


Only arrays have index, so it is only possible to access values through variables that are somehow, arrays. Scalar variables cannot be accessed by indexes.

Just remembering that there are two types of arrays, don’t forget the array associative. Also consider strings as arrays, after all a string is a array characters. So technically it can be called scalar, but it doesn’t behave like a scalar type.

So in your code, eventually, it might be interesting to have a array or a scalar value assigned to a single variable, this is one of the advantages of dynamic typing languages. But to know how to access the data, first one must test the type of the variable to make an appropriate decision according to the result of this test.

Your code can be easily tested and you can see that the result will not be as expected when the value is scaled. He will probably consider that he is taking an indefinite amount and will not present anything.

2

Yes you can access a scalar(simple) variable as an index as long as it is one string this will return the character at that position. This behavior is then not valid for other types like int, float, Boolean.

$str = 'ola mundo';
echo $str[2]; // retorna somente a letra 'a'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.