Home>Article>Backend Development> How to convert array to index array in php
Two conversion methods: 1. Use the array_values() function to convert the array into an index array. The original key name will be converted into a numeric key name starting from 0 and increasing by 1. The syntax "array_values($arr )". 2. Define an empty array, use the foreach statement to loop through the original array, and pass the key values of the original array into the empty array in the loop body. The syntax is "$res=[];foreach($arr as $v){$ res[]=$v;}".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php will convert the array Two methods for indexing arrays
Method 1: Use the array_values() function to convert the array into an index array
array_values() function The function is to return the values of all elements in the array
array_values(array)
It is very simple to use. With only one required parameter, you can return an array containing all the values in the given array, but do not retain the key name. The returned array will be in the form of an indexed array, with array indices starting at 0 and increasing by 1.
Simply put, you can use this function to reset the array key name and convert the key name with confusing string or numerical value into a numeric key name starting from 0 and increasing by 1.
array_values() function is particularly suitable for arrays with confusing element subscripts (numeric keys can be reset), or for converting associative arrays into indexed arrays.
65,"Harry"=>80,"John"=>78,"Clark"=>90,2,3,4); echo "原数组:"; var_dump($arr); $res=array_values($arr); echo "转为索引数组后:"; var_dump($res); ?>
Method 2: Use a foreach loop and an empty array to convert the array into an index array
Use the foreach statement to loop through the original array
In the loop body, pass the key value of the original array into the empty array
65,3,"Harry"=>80,4,"John"=>78,"Clark"=>90); echo "原数组:"; var_dump($arr); $res=[]; foreach($arr as $v){ $res[]=$v; } echo "转为索引数组后:"; var_dump($res); ?>
Explanation:
The syntax of empty array assignment:
$数组变量名[键名] = 值;
When assigning a value to an empty array, you do not need to specify the specific key name within the square brackets value. At this time, the key name value defaults to a numerical value, and increases sequentially starting from 0.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert array to index array in php. For more information, please follow other related articles on the PHP Chinese website!