Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - how to remove all elements of an array after one specified

I have an array like so:

Array ( [740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 [730106] => subsubcat [740107] => and another [730109] => test cat )

I want to remove all elements of the array that come after the element with a key of '720102'. So the array would become:

Array ( [740073] => Leetee Cat 1 [720102] => cat 1 subcat 1 )

How would I achieve this? I only have the belw so far...

foreach ($category as  $cat_id => $cat){
    if ($cat_id == $cat_parent_id){
    //remove this element in array and all elements that come after it 
    }
}

[EDIT] The 1st answer seems to work in most cases but not all. If there are only two items in the original array, it only removes the first element but not the element after it. If there are only two elements

Array ( [740073] => Leetee Cat 1 [740102] => cat 1 subcat 1 )

becomes

Array ( [740073] => [740102] => cat 1 subcat 1 )

Why is this? It seems to be whenever $position is 0.

like image 442
LeeTee Avatar asked Nov 10 '11 18:11

LeeTee


1 Answers

Personally, I would use array_keys, array_search, and array_splice. By retrieving a list of keys using array_keys, you get all of the keys as values in an array that starts with a key of 0. You then use array_search to find the key's key (if that makes any sense) which will become the position of the key in the original array. Finally array_splice is used to remove any of the array values that are after that position.

PHP:

$categories = array(
    740073 => 'Leetee Cat 1',
    720102 => 'cat 1 subcat 1',
    730106 => 'subsubcat',
    740107 => 'and another',
    730109 => 'test cat'
);

// Find the position of the key you're looking for.
$position = array_search(720102, array_keys($categories));

// If a position is found, splice the array.
if ($position !== false) {
    array_splice($categories, ($position + 1));
}

var_dump($categories);

Outputs:

array(2) {
  [0]=>
  string(12) "Leetee Cat 1"
  [1]=>
  string(14) "cat 1 subcat 1"
}
like image 182
Francois Deschenes Avatar answered Nov 09 '22 15:11

Francois Deschenes