Reputation: 1555
I'm reading book about php, and here is task to print elements of array depends on their type;
So i created array $arr = array (5, 'str', 4, 'str1', -100, 10);
, and then using foreach
statement i tried to print elements that are integer
foreach ($arr1 as is_integer($arrelem))
{
print $arrelem;
}
But this gives me an errorFatal error: Can't use function return value in write context in
.
I'm sure there is something wrong with algorithm, but i need advice on how to understand these alhorighms
Upvotes: 0
Views: 76
Reputation: 95101
You can use this example
$arr = array(5,'str',4,'str1',- 100,10);
Example 1 - Waygood
foreach ($arr as $var) {
print $var . ": ";
echo gettype($var), "\n";
}
Example 2
foreach ( $arr as $var ) {
print $var . ": ";
if (is_integer($var)) {
if ($var < 0) {
print "Negative Integer \n";
} else {
print "Positive Integer \n";
}
}
}
Upvotes: 0
Reputation: 212412
$integerValues = array_filter($array1,'is_integer');
$booleanValues = array_filter($array1,'is_bool');
etc
Upvotes: 3
Reputation: 57709
foreach ($arr1 as is_integer($arrelem))
is not allowed
Write it like so:
foreach ($arr1 as $arrelem) {
if (is_integer($arrelem)) {
print "int:" . $arrelem;
} else if (is_string($arrelem)) {
print "string:" . $arrelem;
} else {
print "other:" . $arrelem;
}
}
If this is for debugging you can also use var_dump
, which will give you the type and value of a variable.
Upvotes: 5
Reputation: 30453
It is not correct syntax, after keyword as you may place only name of variable.
Upvotes: 0