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

3

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

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

Follow the example below:

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 it was just a question that came to me when doing something similar.

So, someone would know to answer this question and if the answer is no, why does not it work?

    
asked by anonymous 16.03.2015 / 17:44

2 answers

4

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

Just remembering that there are two types of arrays , do not forget associative array . Also consider strings as arrays , after all in the background a string is an array character. So technically it can be called scalar, but it does not behave like a scalar type.

Then in your code, it may be interesting to have an array or a scalar value assigned to a single variable, this is one of the advantages of dynamic typing languages . But to know what should be the way to access the data, you must first 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 expected when the value is scaled. He will probably consider that he is taking an indefinite value and will not present anything.

    
16.03.2015 / 18:16
2

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

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