PHP array index problem

The following code:

<?php
$test_array = array();
$test_array['string_index'] = "data in string index";
$test_array[] = "data in index 0";
$test_array[] = "data in index 1";
$test_array[] = "data in index 2";

foreach($test_array as $key => $val)
{
    if($key != 'string_index')
    {
        echo $val."<br>";
    }
}
?>

gives the result:

data in index 1
data in index 2

The question is where is the "data at index 0" ??? How to get elements from numerical indices 0-n? In addition, if I change "string_index" to something else that does not exist, it repeats everything except [0]. Plz explain this to me.

Thnx in advance

+3
source share
4 answers

This is because the data "index 0" has the key 0. In PHP, 0(number zero), '0'(string zero) and ''(empty string) are equivalent - they can get typecast to each other. If you just did print_r($test_array), you will get

Array
(
    [string_index] => data in string index
    [0] => data in index 0
    [1] => data in index 1
    [2] => data in index 2
)

(!==), . 0 !== 'string index' true, , .

:

:

echo "key: $key (", gettype($key), ") val: $val (", gettype($val), ")\n";
if($key != 'string_index') {
    echo "$key != 'string_index'\n";
} else {
    echo "$key == 'string_index'\n";
}

:

key: string_index (string) val: data in string index (string)
string_index == 'string_index'
key: 0 (integer) val: data in index 0 (string)
0 == 'string_index'
key: 1 (integer) val: data in index 1 (string)
1 != 'string_index'
key: 2 (integer) val: data in index 2 (string)
2 != 'string_index'

, - , , / PHP.

+12

::) ! == not!=

<?php
$test_array = array();
$test_array['string_index'] = "data in string index";
$test_array[0] = "data in index 0";
$test_array[] = "data in index 1";
$test_array[] = "data in index 2";

foreach($test_array as $key => $val)
{
    if($key !== 'string_index')
    {
        echo $val."<br>";
    }
}
?>

.

+3

=== ! == ==,!= , .

 <?php
     $test_array = array();
     $test_array['string_index'] = "data in string index";
     $test_array[] = "data in index 0";
     $test_array[] = "data in index 1";
     $test_array[] = "data in index 2";

     foreach($test_array as $key => $val)
     {
        if($key ==='string_index')
        {
           //do something
        }else{
           echo $key.$val."<br>";
        }
     }
 ?>
+1

To clarify:
The reason 0 != 'string_index'why the string is apparently β€œomitted” to an integer in the string / integer comparison, and is string_indexanalyzed until a character that is not a digit is found, thereby evaluating empty string equal to 0.

0
source

Source: https://habr.com/ru/post/1794929/


All Articles