How can I remove a specific item from an array that is stored in a table using PHP?

This is a question posted on Stackoverflow – How can I remove a specific item from an array that is stored in a table using PHP?

The actual issue unknown and it may be related to the Database ORM being used, which I have never sighted before BUT as I spent a lil bit of time looking in to this and ended up writing an answer, I didn’t submit it as it’s not quite addressing the issue but, instead of just deleting it all I thought I’d post it here for reference.

So this was my unposted answer.

Your code appears to work in regards to the removal of the entry from the array… But the indexing will be out of order I.E a Gap will occur.

To simulate this, removing the file “stuff” and working from your code and array example.

NOTE: You can run this in its own file as it’s standalone code.

<?php
// Simulate the Values from the Database
$file_array =  ["166038569262f7799c8af00.jpg", "166038569262f7799caedab.jpg", "166038569262f7799cdc59c.jpg"];
// Simulate the File to Delete from the $file_array
$file_to_delete = "166038569262f7799c8af00.jpg";

$image_sliders = [];
$images = $file_array;

if(!empty($images)) {
    $image_sliders = $images;
    foreach ( $image_sliders as $key=>$value ) {
        echo $key. ' '.$value;
        echo '<br>';;
        if ( $value == $file_to_delete ) {
            unset($image_sliders[$key]);
            $image_sliders = array_values($image_sliders); //Re Index the array
            break;
        }
    }
}
/** @todo  DEBUG */
echo '<pre>';
echo 'LINE: '. __LINE__.'<br>';
var_dump($images);
echo '</pre>';

/** @todo  DEBUG */
echo '<pre>';
echo 'LINE: '. __LINE__.'<br>';
var_dump($image_sliders);
echo '</pre>';  

Or using array_diff to remove an entry by value.

foreach ( $image_sliders as $value ) {
    if ( $value == $file_to_delete ) {
        $image_sliders = array_diff( $image_sliders, array( $file_to_delete ) );
        $image_sliders = array_values($image_sliders);//Re Index the array
        break;
    }
} 

Or you can replace the whole foreach code using array_search..

if(!empty($images)) {
    $image_sliders = $images;
    if (($key = array_search($file_to_delete, $image_sliders)) !== false) {
        unset($image_sliders[$key]);
        $image_sliders = array_values($image_sliders);//Re Index the array
    }
}

And there are other ways to achieve this but that should get you started.

I just found some “other ways” that are worth a read. Deleting an element from an array in PHP


And that is the end of that… Or is it?

Leave a Reply

Your email address will not be published.