Reputation: 115
I am struggling with displaying some content depending on if an array does have a value or not.Every time the code in the else part is executed. What's wrong here? Is there any syntax error with this code? I'm using php laravel.
foreach($now as $v)
{
$arry[$c++]=$v->Code;
}
if($arry==null){
Do Something
}
else{
Do Something else
}
Upvotes: 2
Views: 44641
Reputation: 1
if(!$users->isEmpty()){
return response()->json(['status' => 1, 'data' => $users]);
}else{
return response()->json(['status' => 0, 'msg' => 'no employees found']);
}
Upvotes: 0
Reputation: 174
if ( sizeof($arry) ) { // If more than 0
// Do Something
} else { // If 0
// Do Something else
}
Upvotes: 3
Reputation: 1002
You can use empty()
or count()
or sizeof()
as below :
$a = [];
if(empty($a)) {
echo 'empty' . PHP_EOL;
} else {
echo '!empty' . PHP_EOL;
}
if(count($a) == 0) {
echo 'empty' . PHP_EOL;
} else {
echo '!empty' . PHP_EOL;
}
if(sizeof($a) == 0) {
echo 'empty' . PHP_EOL;
} else {
echo '!empty' . PHP_EOL;
}
echo empty($a) . PHP_EOL; // 1
echo count($a) . PHP_EOL; // 0
echo sizeof($a) . PHP_EOL; // 0
Output :
empty
empty
empty
1
0
0
Upvotes: -1
Reputation: 1509
Better to do if (!empty($arry)) {}
P.S. yes if (!$arry)
do the same, but every person which is not familiar with php or even have little understanding of programming, should understand the code. Whats mean "not array", but if it will be "not empty array" is more clear. It is very straight forward.
Clean code
Upvotes: 3
Reputation: 746
this is not related to Laravel framework
if (count($arry) > 0)
Do Something
else
Do Something else
Upvotes: -2
Reputation: 1646
Always check array before iterate in foreach and check with count function to check its value
if(isset($now) && count($now)>0){
foreach($now as $v) {
$arry[$c++]=$v->Code;
}
}
if(count($arry)>0){
Do Something
}
else{
Do Something else
}
Upvotes: 0
Reputation: 2416
if($arry) {
echo 'The array is not empty';
}
else {
echo 'The array is empty';
}
For more: How can you check if an array is empty?
Upvotes: 7