This question already has answers here:
Invalid argument supplied for foreach()
(20 answers)
Closed 7 years ago.
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '#' error suppressor, but that would be a bit hacky.
There are a million ways to do this.
The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.
In other cases this is what you might need:
foreach ((array) $items as $item) {
print $item;
}
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.
In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array(); is what you really wanted.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:
foreach (($result ? $result : array()) as $item)
echo $item;
Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.
I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.
I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.
All other solutions are quite dirty hacks to me.
foreach((array)$items as $item) {}
i've got the following function in my "standard library"
/// Convert argument to an array.
function a($a = null) {
if(is_null($a))
return array();
if(is_array($a))
return $a;
if(is_object($a))
return (array) $a;
return $_ = func_get_args();
}
Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions
foreach(a($whatever) as $item)....
$foo = array_map(a($array_or_string)....
etc
Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.
foreach (is_array($Items) || is_object($Items) ? $Items : array() as $Item) {
It is a bit of a pain to write, but is the safest way to handle it.
You can check whether $items is actually an array and whether it contains any items:
if(is_array($items) && count($items) > 0)
{
foreach($items as $item) { }
}
Best practice is to define variable as an array at the very top of your code.
foreach((array)$myArr as $oneItem) { .. }
will also work but you will duplicate this (array) conversion everytime you need to loop through the array.
since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.
Related
First of all I'm very sorry for my irrelevant question title, as I did not know how to write it better.
To start with, I am a PHP beginner. I am solving some PHP exercise and I came upon a question I don't know where to start with:
function q3() {
// I am supposed to write stuff here and not change anything to get the question right.
}
function a3($admin = false) {
assertion_group("Question 3");
foreach ($GLOBALS as $k => $v) $$k = $v;
if ($admin) {
$file = q3("edsi.pem");
}
$key = #file_get_contents($file);
$key = substr($key, 0, 4);
assert($key == substr(file_get_contents(__FILE__), 0, 4));
return $key;
}
First of all, I understand what $GLOBALS does, but why assign the $$k to $v (so the $k value to the $v value)? And does $GLOBALS get the values within functions?
How can I set $admin = true? I believe through q3(), but I don't see how...
Next thing that confuses me most is: $file = q3("edsi.pem"). As my q3 function doesn't have any arguments, and that I'm not supposed to add one, how can I use that?!
Thank you all very much in advance for your answer. My apologies again for the very vague question...
EDIT:
With the help of #mario to better understand this whole mess, basically what I had to put in q3 was:
if ($info == 'edsi.pem') {
$info = __FILE__;
return $info;
}
plus add an argument for q3 (q3($info)) and add ?admin=true in the header...
Many thanks again!
First of all, I understand what $GLOBALS does, but why assign the $$k to $v (so the $k value to the $v value)? And does $GLOBALS get the values within functions?
What that foreach … $$k = $v; snippet does is basically extract($GLOBALS);
This isn't a very useful way to pass arguments around. Using global vars only makes sense if they have somewhat descriptive names, and if they're not misused as state flags between different code sections.
And no, globals aren't available in all functions right away. Read up on variable scope.
How can I set $admin = true? I believe through q3(), but I don't see how...
You are confusing the function names here (precisely because they aren't rather useful function names to begin with). You can pass the $admin parameter when calling a3() instead:
a3(true);
Next thing that confuses me most is: $file = q3("edsi.pem"). As my q3 function doesn't have any arguments, and that I'm not supposed to add one, how can I use that?!
The only way to get the argument in q3 is per func_get_arg().
And again really, unless this is an exercise about how not to write code or a tutorial about weird use cases, you shouldn't really bother further.
I have a function that returns an array, and is passed to foreach i.e.
foreach(function() as $val)
Since the array I am returning is declared in a series of if statements, I need to return an empty array if all the if statements are evaluated to false. Is this a correct way to do it?
if (isset($arr))
return $arr;
else
return array();
I would recommend declaring $arr = array(); at the very top of the function so you don't have to worry about it.
If you are doing the check immediately before you return, I do not recommend isset. The way you are using foreach is depending on an array being returned. If $arr is set to a number, for example, then it will still validate. You should also check is_array(). For example:
if (isset($arr) && is_array($arr))
return $arr;
else
return array();
Or in one line instead:
return (isset($arr) && is_array($arr)) ? $arr : array();
But, like I said, I recommending declaring the array at the very top instead. It's easier and you won't have to worry about it.
To avoid complexity, Simply
return [];
Does anyone know of any issues, performance or other, that can occur by casting a variable to an array instead checking it first?
// $v could be a array or string
$v = array('1','2','3');
OR
$v = '1';
instead of:
if (is_array($v)) foreach ($v as $value) {/* do this */} else {/* do this */}
I've started to use:
foreach((array) $v as $value) {
// do this
}
It stops the repetition of code quite a bit - but performance is on my mind, not ugly code.
Also, does anyone know how php handles casting an array to an array? No errors are thrown but does the php engine check if it's a array, then return a result before doing the cast process?
First: Premature optimization is the root of all evil. Never let performance influence your coding style!
Casting to an array allows to some nice tricks, when you need an array, but want to allow a single value
$a = (array) "value"; // => array("value")
Note, that this may lead to some unwanted (or wanted, but different) behaviours
$a = new stdClass;
$a->foo = 'bar';
$a = (array) $a; // => array("foo" => "bar");
However, this one
if(is_array($v)) {
foreach($v as $whatever)
{
/* .. */
}
} else {
/* .. */
}
allows you to decide what should happen for every single type, that can occur. This isn't possible, if you cast it "blindly" to an array.
In short: Just choose the one, that better fits the needs of the situation.
As Felix Kling says above, the best solution is to have your data come from a source that guarantees its type. However, if you can't do that, here's a comparison for 1000000 iterations:
check first: 2.244537115097s
just cast: 1.9428250789642s
(source)
Just casting without checking (using in_array) seems to be (slightly) quicker.
Another option here is this (this can be done inline as well, of course, to avoid the function call):
function is_array($array) {
return ($array."" === "Array");
}
This seems to be slightly faster than is_array, but your mileage may vary.
The problem with casting to an array like this (which is also an option)
if ((array) $v === $v)
Is that it's faster than is_array for small arrays, but disastrously slower for large ones.
I have a foreach loop, that will loop through an array, but the array may not exist depending on the logic of this particular application.
My question relates to I guess best practices, for example, is it ok to do this:
if (isset($array))
{
foreach($array as $something)
{
//do something
}
}
It seems messy to me, but in this instance if I dont do it, it errors on the foreach. should I pass an empty array?? I haven't posted specific code because its a general question about handling variables that may or may not be set.
Just to note: here is the 'safest' way.
if (isset($array) && is_array($array)) {
foreach ($array as $item) {
// ...
}
}
Try:
if(!empty($array))
{
foreach($array as $row)
{
// do something
}
}
That's not messy at all. In fact, it's best practice. If I had to point out anything messy it would be the use of Allman brace style, but that's personal preference. (I'm a 1TBS kind of guy) ;)
I'll usually do this in all of my class methods:
public function do_stuff ($param = NULL) {
if (!empty($param)) {
// do stuff
}
}
A word on empty(). There are cases where isset is preferable, but empty works if the variable is not set, OR if it contains an "empty" value like an empty string or the number 0.
If you pass an empty array to foreach then it is fine but if you pass a array variable that is not initialized then it will produce error.
It will work when array is empty or even not initialized.
if( !empty($array) && is_array($array) ) {
foreach(...)
}
I would say it is good practice to have a 'boolean' other value that is set as 0 (PHP's false) to start, and any time some function adds to this array, add +1 to the boolean, so you'll have a definite way to know if you should mess with the array or not?
That's the approach I would take in an object oriented language, in PHP it could be messier, but still I find it best to have a deliberate variable keeping track, rather than try to analyze the array itself. Ideally if this variable is always an array, set the first value as 0, and use it as the flag:
<?PHP
//somewhere in initialization
$myArray[0] = 0;
...
//somewhere inside an if statement that fills up the array
$myArray[0]++;
$myArray[1] = someValue;
//somewhere later in the game:
if($myArray[0] > 0){ //check if this array should be processed or not
foreach($myArray as $row){ //start up the for loop
if(! $skippedFirstRow){ //$skippedFirstRow will be false the first try
$skippedFirstRow++; //now $skippedFirstRow will be true
continue; //this will skip to the next iteration of the loop
}
//process remaining rows - nothing will happen here for that first placeholder row
}
}
?>
example:
foreach($boxes as $box) {
echo "$box \n";
}
Used to be fairly easy, I could just wrap the foreach around a check like:
if(is_array($boxes) && count($boxes) > 0) {
//foreach loop here
}
Without having to worry about a warning getting thrown if for whatever reason bad input was passed to the $boxes array.
When Iterators, were added to the mix, this no longer works, as Iteratable objects are not arrays. So, I have a few solutions, but am wondering if there is a 'best practice' for this.
// 1:
if($boxes instanceof Traversable && count($boxes) > 0) {
//foreach loop here
}
// 2:
if($boxes && count($boxes) > 0) {
//foreach loops here
}
There are others, but these seem like the most obvious. Anyone have any suggestions. PHP docs seem to be silent.
You shouldn't have the count($array) > 0 part, because a) foreach works fine with empty arrays, b) objects can be Traversable yet not be Countable and c) the value returned by count() may even (for objects) be disconnected from the number of items the traversal will yield.
And #1 there is different from #2; since $boxes instanceOf Traversable is not the same as $boxes. Also note that internally arrays don't implement Traversable.
I would go with
if (is_array($boxes) || $boxes instanceof Traversable) {
foreach (...)
}
This still doesn't guarantee that the traversal will be successful; the iteration may throw an exception at any point. In particular, for some classes it may not make sense to traverse them more than once.
I think generally in these cases you would probably know that the variable is going to be iterable if it is not null or false etc., so I would be happy to just do:
if ($boxes) {
foreach ($boxes as $box) {}
}
Maybe that is naive though
One possibility depending on your php version is a cast:
<?php
$a = array('foo', array('bar'));
foreach ($a as $thing)
foreach ((array) $thing as $item) // <-- here
echo "$item\n";
?>
This test will give true for both arrays and array-like objects
if (is_array($obj) || $obj instanceof Traversable) {
foreach ($obj as $item) { /* foreach loop is safe here */
}
}
In PHP5 you can iterate over any array or object so..
if (is_array($my_var) || is_object($my_var)) {
// Do some foreachin'
}