• Page:
  • 1

Insert element in array before / after a specific key

ONLINE

Insert element in array before / after a specific key

3 months ago
Hi All,

Recently, I needed to Insert elements before / after a specific key in array code is running in Loop. I used the below two functions for respective -
function array_insert_before($key,&$array,$new_key,$new_value='NA'){
		if(array_key_exists($key,$array)){
			$new = array();
			foreach($array as $k=>$value){
				if($k === $key){
					$new[$new_key] = $new_value;
				}
				$new[$k] = $value;
			}
			return $new;
		}
		return false;
	}

function array_insert_after($key,&$array,$new_key,$new_value='NA'){
		if(array_key_exists($key,$array)){
			$new = array();
			foreach($array as $k=>$value){
				$new[$k] = $value;
				if($k === $key){
					$new[$new_key] = $new_value;
				}
			}
			return $new;
		}
		return false;
	}


I am using the array_insert_after() in below manner -


foreach($headers as $key=>$value){
	if(!isset($decode[$value])){ //$decode is a predefined array which has its own keys & values also we need to insert the elements in this array only
		$decode = $this->array_insert_after($headers[$key-1],$decode,$value);
	}
}


This is working perfectly for me.
Last Edit: 3 months ago by Rajat Pal.
The following user(s) said Thank You: Neemit Shastri, Khurram Shaikh, Aadarsh Jain, Ashwin Verma
  • Page:
  • 1

Upcoming Events

Who's Online