Antari24 Antari24 - 5 months ago 12
PHP Question

Delete PHP array from PHP array by value

I want to delete a whole array within an array selected by a specific value.
This is the code I got so far.

Since I'm unsetting the array with all the subarrays and then inserting back the subarrays what could (I think) lead to huge performance problems with larger or more arrays.

So my question is there a way to optimise the code below or just remove the one array and leave the rest untouched?

Thanks :)

UPDATED CODE

<?php

$currentValue = '#6';

$otherValue = [ "ID" => '2', "valueID" => '#6' ];
$otherValue2 = [ "ID" => '3', "valueID" => '#7' ];
$otherValue3 = [ "ID" => '4', "valueID" => '#8' ];
$valueArray = [ $otherValue, $otherValue2, $otherValue3 ];

echo 'current value: '.$currentValue;
echo '<br><br>';

print_r($valueArray);
echo '<br><br>';

$valueArray = array_filter($valueArray, function ($value) use ($currentValue) {
return $value['valueID'] !== $currentValue;
});

print_r($valueArray);

?>

Answer

Your code will return the wrong result in many cases, for instance when the searched for value is not found at all, or in the last sub-array. This is because of the following lines:

unset($valueArray);

and

$valueArray[] = $value;

That first statement destroys any previous result made with the second. Or if the first is never executed, the second just adds to the original array, making it twice its original size.

Instead you could use array_filter:

$valueArray = array_filter($valueArray, function ($value) use ($currentValue) {
    return array_search($currentValue, $value) === false;
});

See it run on eval.in.

As @shudder noted in comments, it is strange that you want to search the value in all the keys. From the example you have given it looks like you are expecting to find it under the valueID key.

In that case you can optimise your code and do:

$valueArray = array_filter($valueArray, function ($value) use ($currentValue) {
    return $value['valueID'] !== $currentValue;
});

See it run on eval.in.

Comments