user4939482
user4939482

Reputation:

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 :)

<?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>';
foreach( $valueArray as $key => $value ) {
    echo 'Value: ';
    print_r($value); 
    if(($key = array_search($currentValue, $value)) !== false) {
        echo ' - true, '.$currentValue.' is in $value<br>';

        unset($value);
        unset($valueArray);

        if( isset($value) ) {
            print_r($value);
            echo '<br>';
        } else {
            echo '$value was deleted<br><br>';
        }
    } else {
        echo ' - false<br>';
        $valueArray[] = $value;
    }

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

?>

Upvotes: 1

Views: 68

Answers (1)

trincot
trincot

Reputation: 351084

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.

Upvotes: 1

Related Questions