skip to Main Content

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


  1. You could use array_filter:

    if (!array_filter($stock, fn ($v) => !is_null($v))) {
        // all-null entries!
        // ....
    }
    
    Login or Signup to reply.
  2. What you want to check is not the index for null but the value, you can simply do so by using Collections:

    $collection = collect($array);
    
    $notNull = $collection->filter()
        ->isNotEmpty();
    

    filter will go over each value and if it is null, 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 return false, exactly what you want, get true when you have at least a single value that is not null.

    Login or Signup to reply.
  3. You can use array_filter to get an array with any non-empty values, so it will exclude null, false, and 0.

    $not_empty = array_filter($stocks['stock']);
    if(!$count($not_empty)) {
    return back()->with('error', 'Quantity must be filled in!');
    }
    

    If you want to allow 0, you can add a callback function to check for false/null instead.

    Login or Signup to reply.
  4. Simply use array_filter to remove all NULL values and count the returned array like

    return (bool) count(array_filter($stocks['stock'], fn($v) => $v !== null))))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search