Home  >  Article  >  Backend Development  >  How to get the position of a value in an array in php

How to get the position of a value in an array in php

青灯夜游
青灯夜游Original
2022-05-07 21:03:282938browse

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.

How to get the position of a value in an array in php

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);

How to get the position of a value in an array in php

  • 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;

How to get the position of a value in an array in php

  • 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

1,"name"=>"李华","age"=>23,"1"=>1,"id2"=>52);
$values=array_values($array);
var_dump($values);
$index=array_search(23,$values)+1;
echo "数值23在数组的第 ".$index." 位";
?>

How to get the position of a value in an array in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn