Home >Backend Development >PHP Problem >How to get the position of a value in an array in php
Acquisition method: 1. Use "array_values(array)" to convert the specified array into an index array; 2. Use "array_search(value, index array)" to search for values in the index array and return the corresponding index. Value (subscript); 3. Use the "index value 1" statement to obtain the position value of the element in the array.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php gets the value in Which position in the array
Implementation method:
Use array_values() to convert the specified array into an index array ( Mainly for associative arrays, if it is an index array, there is no change).
$array=array("id"=>1,"name"=>"李华","age"=>23,"1"=>1,"id2"=>52); var_dump($array); $values=array_values($array); var_dump($values);
Use array_search() to search for the specified value in the index array, and if successful, return the corresponding key name (index value or subscript).
(The key name of the index array is of course a numeric value, and each number corresponds to the position of an array element in the array)
$index=array_search(23,$values); echo $index;
The key name of the index array starts counting from 0, so add 1 to the key name
Complete implementation Code: Check the position of value 23 in the array
<?php header("Content-type:text/html;charset=utf-8"); $array=array("id"=>1,"name"=>"李华","age"=>23,"1"=>1,"id2"=>52); $values=array_values($array); var_dump($values); $index=array_search(23,$values)+1; echo "数值23在数组的第 ".$index." 位"; ?>
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to get the position of a value in an array in php. For more information, please follow other related articles on the PHP Chinese website!