SoFunction
Updated on 2025-03-09

PHP implements a method to insert elements before the key specified in the associative array

This article describes the method of PHP implementing inserting elements before the key specified in the associative array. Share it for your reference, as follows:

A PHP associative array 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 the specified key? The following code inserts $data before the key named $key of the associative array $array :

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{  // If $key is not specified or cannot be found, add it directly to the end    return array_merge($array, $data);
  }
}

For more information about PHP related content, please check out the topic of this site:Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《Summary of common functions and techniques for php》、《Summary of PHP error and exception handling methods》、《Introduction to PHP basic syntax》、《PHP object-oriented programming tutorial》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.