0

Say I have the following:

Array(
[0] => Array
    (
        [id] => 1
        [item] => first item
    )

[1] => Array
    (
        [id] => 3
        [item] => second item
    )

[2] => Array
    (
        [id] => 5
        [item] => third item
    )

)

I want to delete the item with id = 5. I know I can loop through the array and unset, but I'm hoping for a more direct/efficient solution.

4 Answers 4

3

If you cannot make the IDs the keys of the outer array (then you could simply use unset($arr[5]);), looping over the array is indeed the way to dg.

foreach($arr as $key => $value) {
    if($value['id'] === 5) {
        unset($arr[$key]);
        break;
    }
}

Another option would be using array_filter - that's less efficient though since it creates a new array:

$arr = array_filter($arr, function($value) {
    return $value['id'] !== 5;
});
Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you create the array with the keys set as the ID's? E.g:

Array(
[1] => Array
    (
        [id] => 1
        [item] => first item
    )

[3] => Array
    (
        [id] => 3
        [item] => second item
    )

[5] => Array
    (
        [id] => 5
        [item] => third item
    )

)

You can then write:

<?php    
unset($array[5]); // Delete ID5
?>

2 Comments

I'm dealing with some older JSON and can't manipulate it, unless I could translate the array somehow...
mmm I think you're only option maybe to loop through if you can't manipulate
1

For Multi level nested array

<?php
    function remove_array_by_key($key,$nestedArray){
        foreach($nestedArray as $k=>$v){
            if(is_array($v)){
                remove_array_by_key($key,$v);
            } elseif($k==$key){
                unset($nesterArray[$k]);
            }
        }
        return $nestedArrat;
    }
?>

Comments

0

The most efficient way would be to have 2 arrays.

ID => Index
Index => Object (your current array)

Search for ID in your ID => Index helper array and the value will be the Index for your main array, then unset them both.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.