Home >Backend Development >PHP Tutorial >Tutorial on parsing PHP to insert elements before the specified Key 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 example of this article describes how PHP implements inserting elements before the Key specified in the associative array. Share it with everyone for your reference, 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 what if you want to insert an element before a specified 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); } }
The above is the detailed content of Tutorial on parsing PHP to insert elements before the specified Key in an associative array. For more information, please follow other related articles on the PHP Chinese website!