PHP Delete an array section to a specific key value

I have an array that is in a specific order, and I just want to trim part of the array, starting from the first index, to the index of the 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" appears (like a string). So the resulting array will be something like ...

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

Thanks Ian

+4
source share
3 answers

In 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

+7
source
 $newarray = array_slice($array,2,-1,true); 
0
source

Yes, you need to use the array_slice () function in php to solve ur ..............

Sample code below

 ` $input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2); // returns "c", "d", and "e" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", and "c" // note the differences in the array keys print_r(array_slice($input, 2, -1)); print_r(array_slice($input, 2, -1, true)); 

`

The above code gives u the following output:

Array ([0] => c [1] => d) array ([2] => c [3] => d)

0
source

Source: https://habr.com/ru/post/1338828/


All Articles