Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_push error

My code is as below,

$products = array();
for($i=0; $i < sizeof($sales); $i++){
    if(!in_array($sales[$i]['Product']['product'], (array)$products)){
        $products = array_push((array)$products, $sales[$i]['Product']['product']);
    }           
}

I'm getting an error called Fatal error: Only variables can be passed by reference...

I'm using php5

like image 795
Irawana Avatar asked Oct 31 '25 01:10

Irawana


1 Answers

You don't use array_push like that, that's your basic problem. You're trying to fix an error you're producing by casting $products to an array, which causes a new error. You use array_push like this:

array_push($products, ...);

You do not assign the return value back to $products, because the return value is the new number of elements in the array, not the new array. So either:

array_push($products, $sales[$i]['Product']['product']);

or:

$products[] = $sales[$i]['Product']['product'];

Not:

$products = array_push($products, $sales[$i]['Product']['product']);

and most certainly not:

$products = array_push((array)$products, $sales[$i]['Product']['product']);

Please RTM: http://php.net/array_push

like image 77
deceze Avatar answered Nov 01 '25 16:11

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!