0

I am trying to create a condition to check if all value in the array is 0. here's the example of the array.

array:4 [▼
  0 => "0"
  1 => "100"
  2 => "200"
  3 => "100"
]

here's the condition I am trying to fix

    //update the status of the order
    if(empty($input['remainingDeliveries'])) {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus)
        {
            $setStatus->status_id = 3;
        }      
        $setStatus->save();

The $input['remainingDeliveries'] carrying the array.

    } else {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus)
        {
            $setStatus->status_id = 4;
        }      
        $setStatus->save();
    }

at first, I thought my condition is ok but when I try to create a record with this array value,

array:4 [▼
  0 => "152"
  1 => "0"
  2 => "0"
  3 => "0"
]

it triggers the ELSE

what is the proper way to do it? thanks in advance!

2 Answers 2

1

Try

// Filter. The $result array will be empty if all values equal "0".
$result = array_filter($inputArray, function($item) {
    // This should return a boolean value. True means discard, false means keep.
    return $item === '0';
});
if(!count($result)) {
  // all empty thus everything was "0".
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could try Laravel's Collection class to check the array:

if( collect($input['remainingDeliveries'])->every(function($value, $key){
    return $value == '0';
}) ) {
    // they are all '0'
}

https://laravel.com/docs/5.8/collections#method-every

1 Comment

What is not working? Are you getting an error? Or is it not correctly detecting non-zero items in your array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.