Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zaster's avatar

Cannot use a scalar value as an array

I want to do something like this

$po_items = 0;
        foreach($cost_items as $cost_item){
            if ($cost_item->status == 0) {
                $po_items[] = $cost_item->po_item;                
             }
        }
        
        if ($po_items == 0) {
            return redirect()->route('employee.poitem.pending');
        }

When $po_items[] is empty i need to redirect to the named route

The error comes when it goes through the first if statement

Only

        foreach($cost_items as $cost_item){
            if ($cost_item->status == 0) {
                $po_items[] = $cost_item->po_item;                
             }
        }

was working fine before, unless the code breaks afterwards when $po_items[] nothing is assigned to $po_items[]

0 likes
6 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Do this instead

$po_items = [];
        foreach($cost_items as $cost_item){
            if ($cost_item->status == 0) {
                $po_items[] = $cost_item->po_item;                
             }
        }
        
        if (count($po_items) === 0) {
            return redirect()->route('employee.poitem.pending');
        }
HUGE_DICK_10_INCHES's avatar

@RESIN - Use just count(), if there is something it will return true or false like:


$a = [];

if(count($a)) {
    echo 'a';
}else{
    echo 'b';
}

Otherwise he can use $po_items = $cost_items->where('status', 0);

Sinnbeck's avatar

I know :) Just thought it would be good for the person to learn things little by little. In their case it would then be.

 if (!count($po_items)) {
            return redirect()->route('employee.poitem.pending');
        }
zaster's avatar

@resin

$po_items = [];
        foreach($cost_items as $cost_item){
            if ($cost_item->status == 0) {
                $po_items[] = $cost_item->po_item;                
             }
        }
        
        if (count($po_items) == 0) {
            return redirect()->route('employee.poitem.pending');
        }
 if (count($po_items) == 0) {   

Will also work right ? I tested , no issue

Please or to participate in this conversation.