Remove empty array elements

2018-12-31 04:06发布

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

foreach($linksArray as $link)
{
    if($link == '')
    {
        unset($link);
    }
}
print_r($linksArray);

But it doesn't work, $linksArray still has empty elements. I have also tried doing it with the empty() function but the outcome is the same.

25条回答
低头抚发
2楼-- · 2018-12-31 04:41
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));

print_r($b)
查看更多
旧时光的记忆
3楼-- · 2018-12-31 04:41

Just want to contribute an alternative to loops...also addressing gaps in keys...

In my case I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.)

I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/

The combination of array_filter and array_slice does the trick.

$example = array_filter($example); $example = array_slice($example,0);

No idea on efficiencies or benchmarks but it works.

查看更多
其实,你不懂
4楼-- · 2018-12-31 04:41

As per your method, you can just catch those elements in an another array and use that one like follows,

foreach($linksArray as $link){
   if(!empty($link)){
      $new_arr[] = $link
   }
}

print_r($new_arr);
查看更多
十年一品温如言
5楼-- · 2018-12-31 04:44

I use the following script to remove empty elements from an array

for ($i=0; $i<$count($Array); $i++)
  {
    if (empty($Array[$i])) unset($Array[$i]);
  }
查看更多
不流泪的眼
6楼-- · 2018-12-31 04:44

try this ** **Example

$or = array(
        'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
        'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
        'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
        'PersonalInformation.dob' => $this->request->data['User']['dob'],
        'User.email' => $this->request->data['User']['email'],
    );



 $or = array_filter($or);

    $condition = array(
        'User.role' => array('U', 'P'),
        'User.user_status' => array('active', 'lead', 'inactive'),
        'OR' => $or
    );
查看更多
路过你的时光
7楼-- · 2018-12-31 04:45

use array_filter function to remove empty values:

$linksArray = array_filter($linksArray);
print_r($linksArray);
查看更多
登录 后发表回答