Home > Article > Backend Development > Detailed explanation of how PHP inserts elements before the Key specified in an associative array
This article mainly introduces the method of PHP to insert elements before the Key specified in the associative array, involving PHP's array traversal, judgment, acquisition, insertion and other related operation skills. Friends in need can refer to it
The details are as follows:
PHP associative arrays can insert new elements in three ways:
1. $array[$insert_key] = $insert_value;
2. $array = array_merge($array, $insert_array);
3. $array = $array $insert_array;
But if you want to specify What about inserting elements before the key? The following code inserts $data into the associative array $array before the key named $key:
function wpjam_array_push($array, $data=null, $key=false){ $data = (array)$data; $offset = ($key===false)?false:array_search($key, array_keys($array)); $offset = ($offset)?$offset:false; if($offset){ return array_merge( array_slice($array, 0, $offset), $data, array_slice($array, $offset) ); }else{ // 没指定 $key 或者找不到,就直接加到末尾 return array_merge($array, $data); } }
php array function array_unique() removes duplicate values in the array
Summary of how to use php array search function
##
The above is the detailed content of Detailed explanation of how PHP inserts elements before the Key specified in an associative array. For more information, please follow other related articles on the PHP Chinese website!