-1

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...

grazdev
  • 1,082
  • 2
  • 15
  • 37
  • You need to loop over each array element and check if id = x and then delete the element. it is O(n) and efficient. – raviolican Mar 09 '19 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. – grazdev Mar 09 '19 at 10:56

1 Answers1

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136