Home > Backend Development > PHP Tutorial > PHP example explains how to insert elements before the Key specified in the associative array

PHP example explains how to insert elements before the Key specified in the associative array

怪我咯
Release: 2023-03-10 14:30:02
Original
1632 people have browsed it

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);
  }
}
Copy after login

The above is the detailed content of PHP example explains how to insert elements before the Key specified in the associative array. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template