PHP instance details how to insert an element before the key specified in the associative array

Source: Internet
Author: User
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);  }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.