patternphpMinor
!empty() check before a foreach statement
Viewed 0 times
statementemptyforeachbeforecheck
Problem
Is this the best way to prevent that
foreach loop from happening if $terms doesn't exist?$terms = get_the_terms( $postid, 'fecha' );
if(!empty($terms)) {
foreach($terms as $term) {
$myterm = $term->slug;
if(in_array($myterm, $queried_terms)) {continue;}
$queried_terms[] = $myterm;
}
}Solution
The loop won't be executed if
As such: you don't need the empty check. It doesn't hurt, but it's simply not required.
If
You can just cast it to an array before use:
The code would work with or without casting to an array - the only difference is that if
if this is part of another function
you can simply return-early to keep your code concise:
But, any way you slice it - the empty check isn't strictly required, and deeper code nesting is something to be aware of and avoid.
$terms is false/null/an empty array.As such: you don't need the empty check. It doesn't hurt, but it's simply not required.
If
$terms is sometimes not an arrayYou can just cast it to an array before use:
$terms = get_the_terms( $postid, 'fecha' );
foreach((array) $terms as $term) {
$myterm = $term->slug;
if(in_array($myterm, $queried_terms)) {
continue;
}
$queried_terms[] = $myterm;
}The code would work with or without casting to an array - the only difference is that if
$terms is not an array, a notice would be thrown without it. if this is part of another function
you can simply return-early to keep your code concise:
function foo() {
$terms = get_the_terms( $postid, 'fecha' );
if (!$terms) {
return array();
}
$queried_terms = array();
foreach($terms as $term) {
$myterm = $term->slug;
if(in_array($myterm, $queried_terms)) {
continue;
}
$queried_terms[] = $myterm;
}
return $queried_terms;
}But, any way you slice it - the empty check isn't strictly required, and deeper code nesting is something to be aware of and avoid.
Code Snippets
$terms = get_the_terms( $postid, 'fecha' );
foreach((array) $terms as $term) {
$myterm = $term->slug;
if(in_array($myterm, $queried_terms)) {
continue;
}
$queried_terms[] = $myterm;
}function foo() {
$terms = get_the_terms( $postid, 'fecha' );
if (!$terms) {
return array();
}
$queried_terms = array();
foreach($terms as $term) {
$myterm = $term->slug;
if(in_array($myterm, $queried_terms)) {
continue;
}
$queried_terms[] = $myterm;
}
return $queried_terms;
}Context
StackExchange Code Review Q#11779, answer score: 9
Revisions (0)
No revisions yet.