In PHP development, arrays are the most common data type. We often need to operate on them, including obtaining the value of the array, modifying, adding, deleting and other operations. In array operations, key and value are very important concepts, because we use keys to find and operate data in the array. But sometimes we find that our program does not output the keys of the array as we expected. Why is this?
Problem description:
In PHP, when outputting the key of a two-dimensional array, the key may not be displayed normally. The following is a simple example:
<?php $arr = array( array('name'=>'Jack', 'age'=>20), array('name'=>'Lucy','age'=>18), ); foreach($arr as $key => $value){ echo $key."</br>"; } ?>
The expected output is:
0 1
But the actual output is:
name age name age
This shows that the current program does not produce the results we expected Output the keys of the array. So what is the reason for this problem?
Cause of the problem:
The function of the array key is to mark the corresponding value. In fact, the key in the two-dimensional array is not a sequence starting from 0, but a string. For example, the $arr array above, whose keys are 0 and 1, is the following array:
array('name'=>'Jack', 'age'=>20) array('name'=>'Lucy','age'=>18)
The output "name" and "age" are the string keys of the two-dimensional array.
Problem Solution:
So how can we output the digital key we want? Two solutions are recommended here:
Solution 1: Use for loop to output key
Using for loop to output key is a simple and direct method. We can output the corresponding key through loop. Digital key. For example:
<?php $arr = array( array('name'=>'Jack', 'age'=>20), array('name'=>'Lucy','age'=>18), ); for($i=0; $i<count($arr); $i++){ echo $i."</br>"; } ?>
In this way, the desired digital key can be perfectly output. The result is:
0 1
Solution 2: Use the array_keys function
The array_keys function is built-in in PHP A function that can return all the key values in an array. With the array length function count(), we can easily output the numeric key. For example:
<?php $arr = array( array('name'=>'Jack', 'age'=>20), array('name'=>'Lucy','age'=>18), ); print_r(array_keys($arr))."</br>"; for($i=0; $i<count($arr); $i++){ echo $i."</br>"; } ?>
In this way we can also output the expected result "0, 1".
Summary:
Using arrays in PHP is a very common operation. When operating arrays, we need to understand the functions and relationships of the key and value of the array. When we get results that are not in line with expectations, don't be anxious and think more about analyzing solutions to problems. This is also a good opportunity to improve your programming skills and logical thinking.
The above is the detailed content of What should I do if PHP does not display the key of the two-dimensional array?. For more information, please follow other related articles on the PHP Chinese website!