0

Consider this array:

$userBookmarks = [
    [
        "id": 10000,
        "dateAdded": 1552127606
    ],
    [
        "id": 20000,
        "dateAdded": 1552127610
    ],
    [
        "id": 30000,
        "dateAdded": 1552127614
    ]
]

Suppose I know the ID is 10000 and I want to remove the child array where the value of id is 10000, what is the most efficient way so I can remove the entire child array and be left with this:

$userBookmarks = [
    [
        "id": 20000,
        "dateAdded": 1552127610
    ],
    [
        "id": 30000,
        "dateAdded": 1552127614
    ]
]

My "closest" attempt:

for( $i = 0; $i < count( $userBookmarks ); $i++ ) {

    $currentBookmark = $userBookmarks[ $i ]; 

    if( $currentBookmark['id'] == $newBookmarkID ) {
        unset( $currentBookmark ); 
        break; 
    } else {
        $userBookmarks[] = $newBookmark; 
    }

}

But it's really not doing anything...

2
  • You need to loop over each array element and check if id = x and then delete the element. it is O(n) and efficient. Commented Mar 9, 2019 at 10:51
  • Yes, the id values are unique. I did try a few things with loops and unset but I'm very new to arrays and can't make it work. I also researched but all questions seem to be about deleting elements inside arrays, not the arrays themselves. Commented Mar 9, 2019 at 10:56

1 Answer 1

0

A simple thing to fix.

You need to unset() the original reference to the subarray.

Change:

unset( $currentBookmark );

to:

unset( $userBookmarks[ $i ] ); 

The "functional" alternative would look like this:

$userBookmarks = [
    ["id" => 10000, "dateAdded" => 1552127606],
    ["id" => 20000, "dateAdded" => 1552127610],
    ["id" => 30000, "dateAdded" => 1552127614]
];

$newBookmarkID = 10000;

$userBookmarks = array_filter($userBookmarks, function ($v) use ($newBookmarkID) {
        return $v['id'] != $newBookmarkID;
    });

var_export($userBookmarks);

Demonstration: https://3v4l.org/uhDB2

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.