Jeroen
Jeroen

Reputation: 167

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); 
    }

Upvotes: 3

Views: 1819

Answers (3)

Zemistr
Zemistr

Reputation: 1049

foreach($new_cats as $newcat_i => $newcat) {
    $newcat = trim($newcat);

    if($newcat == ' ' || $newcat == '') {
        unset($new_cats[$newcat_i]);
    }
}

OR

$new_cats = array_filter(
    $new_cats, function ($value) {
        $value = trim($value);

        return $value != '' && $value != ' ';
    }
);

Final code is:

if(Input::get('addcategorie')) {
    $new_cats = array();
    foreach(explode(',', Input::get('addcategorie')) as $categorie) {
        $categorie = Categorie::firstOrCreate(array('name' => $categorie));

        array_push($new_cats, $categorie->id);
    }

    $new_cats = array_filter(
        $new_cats, function ($value) {
            $value = trim($value);

            return $value != '' && $value != ' ';
        }
    );

    $workshop->categories()->attach($new_cats);
}

Upvotes: 0

Patrick Maciel
Patrick Maciel

Reputation: 4944

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.

Upvotes: 4

zavg
zavg

Reputation: 11061

You should use the following code to unset in foreach:

foreach($new_cats as $key => $newcat) {
    if(yourCondition) {
        unset($new_cats[$key])
    }
}

Upvotes: 1

Related Questions