Solved

PHP: Remove items from an array if foobar empty

Posted on 2010-09-16
2
249 Views
Last Modified: 2012-05-10
If foobar is empty then I want to remove the entire item from my array.
<?php

$a = array();
$a[]=array('id'=>1,'Name'=>'Abc','foobar'=>null);
$a[]=array('id'=>2,'Name'=>'Jkl','foobar'=>'Hello');
$a[]=array('id'=>3,'Name'=>'Qrs','foobar'=>'Test');
$a[]=array('id'=>4,'Name'=>'Xyz','foobar'=>'');

echo '<pre>';
print_r($a);
echo '</pre>';

?>

Open in new window

0
Comment
Question by:hankknight
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 10

Expert Comment

by:Tyler Laczko
ID: 33693603
<?php

$a = array();
$a[]=array('id'=>1,'Name'=>'Abc','foobar'=>null);
$a[]=array('id'=>2,'Name'=>'Jkl','foobar'=>'Hello');
$a[]=array('id'=>3,'Name'=>'Qrs','foobar'=>'Test');
$a[]=array('id'=>4,'Name'=>'Xyz','foobar'=>'');

for($i=0; $i<array_len($a); $i++)
{
  if($a[$i]['foobar'] == '')
  {
    $a[$i] = NULL;
  }
}
echo '<pre>';
print_r($a);
echo '</pre>';

?>
0
 
LVL 10

Accepted Solution

by:
Tyler Laczko earned 500 total points
ID: 33693935
sorry. this is MUCH BETTER!!!!


<?php

$a = array();
$a[]=array('id'=>1,'Name'=>'Abc','foobar'=>null);
$a[]=array('id'=>2,'Name'=>'Jkl','foobar'=>'Hello');
$a[]=array('id'=>3,'Name'=>'Qrs','foobar'=>'Test');
$a[]=array('id'=>4,'Name'=>'Xyz','foobar'=>'');

foreach($a as $a1)
      if($a1['foobar'] != '' && $a1['foobar'] != NULL)
            $new_array[] = $a1;
      
echo '<pre>';
print_r($new_array);
echo '</pre>';


?>
<?php

$a = array();
$a[]=array('id'=>1,'Name'=>'Abc','foobar'=>null);
$a[]=array('id'=>2,'Name'=>'Jkl','foobar'=>'Hello');
$a[]=array('id'=>3,'Name'=>'Qrs','foobar'=>'Test');
$a[]=array('id'=>4,'Name'=>'Xyz','foobar'=>'');

foreach($a as $a1)
	if($a1['foobar'] != '' && $a1['foobar'] != NULL)
		$new_array[] = $a1;
	
echo '<pre>';
print_r($new_array);
echo '</pre>';


?>

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question