2

I want to delete some data from an array in PHP. Here is the array:

array(4) {
    [0]=> array(1) { ["image"]=> string(20) "w85YrKChBGTZ9fQS.jpg" }
    [1]=> array(1) { ["image"]=> string(20) "3buahEs6rRWFdYez.jpg" }
    [2]=> array(1) { ["image"]=> string(20) "gYPtDrx3sFzkVENB.jpg" }
    [3]=> array(1) { ["image"]=> string(20) "JE3rodDvs6521cFm.jpg" }
} 

Here is my method and where I am deleting:

public function deleteImage(){
    foreach (getCarImages() as $array){
        //var_dump($array).'<br>';
        $index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
        if($index !== FALSE){
            var_dump($index).'<br>';
            unset($array[$index]);
        }else{
            echo '<br>else here';
        }
    }
}

And here is the result of deleteImage()

string(5) "image"

else

here

else

here

else

here

I am confused. How can I delete a nested array from the main array.

2
  • try if($index). if item not found then array_search return empty. Commented Dec 13, 2017 at 7:06
  • please post your getCarImages() function. What is deleteImage() actually going to do? Is there a return value? A file function? A database query? Commented Dec 13, 2017 at 7:15

2 Answers 2

2

If you need to delete a whole subarray from array, then use array_flter function:

public function deleteImage(){
    return array_filter(getCarImages(), function ($v) {
        return $v['image'] != 'w85YrKChBGTZ9fQS.jpg';
    });
}

Update: Anonymous function doesn't know about $imageName variable. You have to use it:

public function deleteImage($imageName = null) 
{ 
    $myarray = array_filter(
        getCarImages(), 
        function ($v) use ($imageName) { return $v['image'] != $imageName; }
    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Its working fine but i want set the dynamic value like this
public function deleteImage($imageName = null){ $myarray = array_filter(getCarImages(), function ($v) { return $v['image'] != $imageName; });
but its giving me this error Message: Undefined variable: imageName
1

You can trans the images as a reference to the function.

public function deleteImage(&$images){
    foreach ($images as $k => $array){
        //var_dump($array).'<br>';
        $index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
        if($index !== FALSE){
            var_dump($index).'<br>';
            unset($images[$k]);
        }else{
            echo '<br>else here';
        }
    }
}

2 Comments

@KrisRoofe Are we allowed to overtly ask for upvotes. I should be doing that on all of my best answers. stackoverflow.com/a/47725480/2943403
@mickmackusa Yeah, you're right. I take your advise.

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.