Two methods: 1. Use array_keys, the syntax "array_keys(array, search value, false|true)" will return an array containing subscripts. 2. Traverse the array and store the subscript into an empty array with the syntax "foreach(array as $k=>$v){$r[]=$k;}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Array array is a set of ordered variables. Each value is called an element. Each element is distinguished by a special identifier called a key (also called a subscript).
So how to find the array subscript in PHP? Two methods are introduced below.
Method 1: Directly use the built-in function array_keys()
array_key() function can get some or all key names (subscripts) in the array, the function syntax The format is as follows:
array_keys($array,$search_value,$strict)
Parameter description is as follows:
===
. array_key() function will return the obtained array key name in the form of an array.
Example 1: All key names
<?php $arr=array("Peter"=>65,"Harry"=>80,"John"=>78,"Clark"=>90); var_dump($arr); var_dump(array_keys($arr)); ?>
Example 2: Key names of specified values
<?php $arr=array("Peter"=>65,"Harry"=>80,"John"=>78,"Clark"=>90); var_dump($arr); var_dump(array_keys($arr,80)); var_dump(array_keys($arr,"80")); var_dump(array_keys($arr,"80",true)); ?>
Method 2: Use the foreach statement to traverse the array and store the key name into an empty array
<?php $arr=array("Peter"=>65,"Harry"=>80,"John"=>78,"Clark"=>90); var_dump($arr); $r=[]; foreach($arr as $k=>$v){ $r[]=$k; } var_dump($r); ?>
Recommended study: "PHP video tutorial》
The above is the detailed content of How to find array subscript in php. For more information, please follow other related articles on the PHP Chinese website!