i want to check all of index in array, if all of index is null return false
, if just one or more not null true
array null
"stock" => array:14 [▼
0 => null
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
7 => null
8 => null
9 => null
10 => null
11 => null
12 => null
13 => null
]
one or more not null
"stock" => array:14 [▼
0 => 1
1 => 1
2 => null
3 => null
4 => null
5 => 2
6 => null
7 => null
8 => null
9 => null
10 => null
11 => null
12 => null
13 => null
]
this my controller
if(isset($stocks['stock'])){
return back()->with('error', 'Quantity must be filled in!');
}
I have tried use isset
, empty
, is_null
, but it doesn’t work
4
Answers
You could use
array_filter
:What you want to check is not the
index
fornull
but thevalue
, you can simply do so by usingCollection
s:filter
will go over each value and if it isnull
, it will not be returned. Once it finished going over each value, the new resulting collection, you just check if you have any value, if you do not have any values,isNotEmpty()
will returnfalse
, exactly what you want, gettrue
when you have at least a single value that is notnull
.You can use array_filter to get an array with any non-empty values, so it will exclude null, false, and 0.
If you want to allow 0, you can add a callback function to check for false/null instead.
Simply use
array_filter
to remove all NULL values and count the returned array like