How can i test a var if its empty or not? i have this array
array($myname,$myhouse,$mywife);
how can i check each of them if it empty or not without using a loop?
How can i test a var if its empty or not? i have this array
array($myname,$myhouse,$mywife);
how can i check each of them if it empty or not without using a loop?
Try isset()
Edit- Use the code posted above, but change the function:
$myvars = array($myname, $myhouse, $mywife);
foreach ($myvars as $value) {
if (isset($value)) {
// Not set
}
}
$myvars = array($myname, $myhouse, $mywife);
foreach ($myvars as $value) {
if (empty($value)) {
// value is empty
}
}
edit: Here is a version which does not use a loop:
$myvars = array($myname, $myhouse, $mywife);
$myvars_filtered = array_filter($myvars, "empty"); // or isset, if you prefer
if (count($myvars_filtered) > 0) {
// one or more values were empty
}
Note that, as Felix commented, when you use "isset"
instead of "empty"
, you will get all values that have a value, instead of the ones that don't. So in that case you need to compare the amount of elements in $myvars
to the count of elements in $myvars_filtered
.
What you're asking for is either impossible or facetious. You either need to explicitly test each variable by name or use a loop to test a dynamic collection of variables.
One line (except the function of course):
function not_empty($val) {
return !empty($val);
}
$result = array_product(array_map('not_empty',$array));
The result is 0
if one variable is empty otherwise 1
.
But of course it won't tell which one is empty. ;)
See array_map, array_product.
If you mean without writing a loop then you can use:
in_array(true, array_map(create_function('$x', 'return empty($x);'),$array));
Implicitly it will of course loop through your array, twice in fact! Once to check the emptiness, then again to check the result. You're better of with a loop you can break when you hit a non_empty value.
Another solution that doesnt use a loop:
<?php
$my_house = "";
$my_name = "Foo Bar";
$my_wife = "Angelina";
$arr = array($my_house, $my_name, $my_wife);
preg_replace("/.+/","-",$arr,-1,$count);
if ($count == 3) {
# everything is filled
} else {
# missing somehwere
}
?>
Sure there are ways to do it. One of them:
<?php
$array = array('myname' => 'Jakob', 'myhouse' => '', 'mywife' => 1);
$empty_elements = array("");
$array = array_keys(array_intersect($array,$empty_elements));
var_dump($array);
?>
outputs:
array 0 => string 'myhouse'
Some other possibilities for a similiar problem (removing the empty ones): http://hasin.wordpress.com/2009/09/16/removing-empty-elements-from-an-array-the-php-way/