PHP is one of the most popular web development languages currently. One of its advantages is its ability to easily handle arrays. In actual development, we often need to retrieve specific values from an array. This article will introduce how to retrieve a certain value from an array in PHP.
In PHP, the most basic value method is to obtain the corresponding value through the array subscript. Suppose there is the following array:
$data = array('id' => 1001, 'name' => 'Tom', 'age' => 18);
To get the value of the $name attribute, you only need to use the following code:
$name = $data['name'];
In this way, the string Tom can be assigned to the variable $name.
In addition to directly using the subscript to obtain the value, you can also use the foreach loop to traverse the array and retrieve the corresponding value. Suppose there is the following array:
$data = array( array('id' => 1001, 'name' => 'Tom', 'age' => 18), array('id' => 1002, 'name' => 'Jerry', 'age' => 20), array('id' => 1003, 'name' => 'Mike', 'age' => 22) );
To get the value of the name attribute of each element, you can use the following code:
foreach ($data as $item) { $name = $item['name']; echo $name . "\n"; }
This will output the three strings Tom, Jerry, and Mike in sequence. .
PHP also provides the list() function to quickly retrieve multiple values from an array. Suppose there is the following array:
$data = array('id' => 1001, 'name' => 'Tom', 'age' => 18);
To assign the values of the id and name attributes to two variables respectively, you can use the following code:
list($id, $name) = array($data['id'], $data['name']);
In this way, 1001 can be assigned to the variable $ id, assign Tom to the variable $name.
After PHP5.5, a new array_column() function has been added to quickly retrieve a column in a two-dimensional array. Suppose there is the following array:
$data = array( array('id' => 1001, 'name' => 'Tom', 'age' => 18), array('id' => 1002, 'name' => 'Jerry', 'age' => 20), array('id' => 1003, 'name' => 'Mike', 'age' => 22) );
To form a new array with the value of the name attribute, you can use the following code:
$names = array_column($data, 'name');
In this way, you can get an array containing three names: Tom, Jerry, and Mike. A new array of strings.
Summary
There are many ways to get a certain value from an array in PHP, the most basic of which is to get the corresponding value through the array subscript. In addition, you can also use foreach loop, list() function, array_column() function and other methods to obtain specific values. Developers can choose different methods to complete the value operation according to specific needs.
The above is the detailed content of How to get a certain value from an array in php. For more information, please follow other related articles on the PHP Chinese website!