This article mainly introduces the implementation of PHP to the associated array to specify the key before inserting elements of the method, involving PHP for the array of traversal, judgment, acquisition, insertion and other related operations skills, the need for friends can refer to the next
This example describes the method by which PHP implements inserting elements before the key specified by the associative array. Share to everyone for your reference, as follows:
The PHP associative array can be inserted into the new element 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 the element before the specified key? The following code will $data insert the associated array $array before the key name is $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{ //not specified $key or not found, directly add to the end of return Array_merge ($array, $data); }}