Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty value of array

i'm looking for a way to remove empty values from a array.

If you see the code below, i'm trying to remove the empty values that get passed through before attaching it to the model. But this hasn't turned out this way so far.

Ofcourse i searched the web before asking, and so i know that trim() doesn't give the desired effect aswell as array_map() and the code below.

Looking for solutions, thanks!

if(Input::get('addcategorie'))
    {
        $new_cats = array();
        foreach(
            explode(
                ',', Input::get('addcategorie')) as $categorie) 
        {
            $categorie = Categorie::firstOrCreate(array('name' => $categorie));
            foreach($new_cats as $newcat)
            if($newcat == ' ' || $newcat == ' ' || $newcat == ''){
                unset($newcat);
            }
            array_push($new_cats, $categorie->id);
        }
        $workshop->categories()->attach($new_cats); 
    }
like image 480
Jeroen Avatar asked Feb 17 '26 12:02

Jeroen


1 Answers

Just use array_filter:

$array = [
    0 => 'Patrick',
    1 => null,
    2 => 'Maciel',
    3 => '&nbsp',
    4 => ' '
];

$filtered = array_filter($array);

$nbsp = array_filter($array, function($element) {
    return $element == '&nbsp' OR  $element == ' ';
});

$clean = array_diff($filtered, $nbsp);

The return is:

array(2) {
  [0]=>
  string(7) "Patrick"
  [2]=>
  string(6) "Maciel"
}

This functions remove all null, empty and &nbsp from your arrays.

like image 93
Patrick Maciel Avatar answered Feb 19 '26 02:02

Patrick Maciel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!