Home » Php » Are PHP Integer array Indexes really numeric?

Are PHP Integer array Indexes really numeric?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Consider this example

<?php
    $test = array("00"=>"A","B","C","D","E");
    print_r($test);
    echo "<br>";

    echo $test[0];
    echo "<br>";
    echo $test["0"];
    echo "<br>";

    echo $test["00"];
    echo "<br>";
    echo $test[00];
?>

Output

Array ( [00] => A [0] => B [1] => C [2] => D [3] => E )

B

B

A

B

Q1. Why is $test[0] same as $test["0"] whereas $test[00] is not same as $test["00"]

Q2. If the answer to Q1 is that because 00 = 0 numerically then why does this array have one index as 00 and another as 0?

Q3. If you cannot access $test["00"] using $test[0] then how do you know which index is numeric and which is string? if both are only numbers

Edit

Based on the answers so far, there is another question in my mind. Here goes Question 4.

Q4. Why is if(00==0) true and if(07==7) false? ( for array indexes)

Q5.

$test = array("00"=>"A","0"=>"B","000"=>"C","0000"=>"D","00000"=>"E");
 echo $test[0];

Why the output is B, should it not be A ? because that is the first element in the array, at 0th position

How to&Answers:

According to the documentation, one of “the […] key casts [that] will occur” is:

Strings containing valid integers will be cast to the integer type. E.g. the key “8” will actually be stored under 8. On the other hand “08” will not be cast, as it isn’t a valid decimal integer.

[link]

Answer:

Q1. Because 00 = 0 numerically

Q2. Because the index is "00" not 00

Try:

$test=array(00=>"A","B","C","D","E");
print_r($test);

/*
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => E
)
*/

Q3.

echo gettype("00");
# string
echo gettype(00);
# integer
echo gettype("0");
# string
echo gettype(0);
# integer

From the manual:
http://php.net/manual/en/language.types.array.php

Strings containing valid integers will be cast to the integer type. E.g. the key “8” will actually be stored under 8. On the other hand “08” will not be cast, as it isn’t a valid decimal integer.

Edited after comment

Q4. I think OP’s question is essentially why the second and the forth behave differently:

php > var_dump("00" === 0);
bool(false)
php > var_dump(00 === 0);
bool(true)
php > var_dump("08" === 8);
bool(false)
php > var_dump(08 === 8);
bool(false)

I have no answer yet.

Answer:

"anystring" == 0; //true
"0000" == 0;      //true

"0" == 0;      //true