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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With