Detailed explanation of how PHP inserts elements before the Key specified in an associative array

墨辰丷
Release: 2023-03-27 10:18:02
Original
1521 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 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);
  }
}
Copy after login

Related recommendations:

php array function array_unique() removes duplicate values ​​in the array

php array function shuffle() and array_rand() detailed explanation of the steps to use the random function

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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!