LeeTee
LeeTee

Reputation: 6601

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.

Upvotes: 6

Views: 8266

Answers (3)

Francois Deschenes
Francois Deschenes

Reputation: 24969

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"
}

Upvotes: 10

keithhatfield
keithhatfield

Reputation: 3273

There are a couple of ways to accomplish this, but using your current structure you could set a flag and delete if the flag is set ...

$delete = false;
foreach($category as $cat_id => $cat){
    if($cat_id == $cat_parent_id || $delete){
        unset($category[$cat_id]);
        $delete = true;
    }
}

Upvotes: -1

Rasmus Styrk
Rasmus Styrk

Reputation: 1346

Try this

$newcats = array();
foreach($category as $cat_id => $cat)
{
    if($cat_id == $cat_parent_id)
        break;

    $newcats[$cat_id] = $cat;
}

$category = $newcats;

Upvotes: -1

Related Questions