-1

is there a way to loop through an array and unset any variables that are =""? i am looking for a faster way to do this aside form writing 4 if else statements.i thought this might work but i don't know if it can be done this way or not.

$a=""
$b="123"
$c=""
$d"123"

$var=array($a,$b,$c,$d)

i am trying to loop through $var array to get

$var= array($b,$d)

is this even possible or should i stick with writing 4 if else statements?

4
  • Show what you've tried. Commented Sep 8, 2014 at 22:18
  • 1
    $var = array_filter($var); Commented Sep 8, 2014 at 22:18
  • foreach($var as $k=>$v) if(!isset($v[0])) unset($var[$k]); or $var = array_filter($var) like @MarkBaker said. Commented Sep 8, 2014 at 22:21
  • array_filter that is what i was looking for thanks Commented Sep 8, 2014 at 22:27

2 Answers 2

0

Have a look here : How to delete object from array inside foreach loop? or here : How do you remove an array element in a foreach loop?

foreach ($array as $key => $value) {
  if($value == "") {
    unset($array[$key]);
  } 
}

Good luck

Sign up to request clarification or add additional context in comments.

Comments

0
$x=["","123","","345"];
$var = array_filter($x);
print_r($var);


The result:

Array
(
    [1] => 123
    [3] => 345
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.