Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Remove section of array before a certain key value

Tags:

arrays

php

I have an array that is in a certain order and I want to just cutoff a portion of the array starting from the first index to the index of a given key.

IE... If i had this array

$array = array("0" => 'blue', "1" => 'red', "2" => 'green', "3" => 'red', "4"=>"purple");

I want to cut off the first part of the array before the key "2" (as a string) is seen. So the end array would be something like...

"2" => 'green'
"3" => 'red'
"4"=>'purple'

Thanks, Ian

like image 563
Ian McCullough Avatar asked Feb 25 '23 04:02

Ian McCullough


1 Answers

For your case you can use

print_r(array_slice($array, 2, count($array),true));

EDIT: For edited question

$cloneArray = $array;
foreach($array as $key => $value){
  if($key == $givenInex)
     break;

  unset($cloneArray[$key]);
} 

Then use $cloneArray

like image 88
Gaurav Avatar answered Mar 05 '23 16:03

Gaurav