Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
$products = (array)$products; //this goes wrong in your method $products = array_push($products, $sales[$i]['Product']['product']); –  Sander Visser Nov 4 '13 at 9:27
add comment

2 Answers 2

up vote 1 down vote accepted

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 RTFM: http://php.net/array_push

share|improve this answer
    
yes, that was the issue. fixed and working fine now. thanks for the help –  Irawana Nov 4 '13 at 10:12
add comment

The first parameter ($products in your case) has to be a reference, therefore a variable has to be passed. You now cast the variable to an array first and the result of that cast cannot be passed by reference since it is not assigned to a variable. You will have to assign it to a variable first or remove the cast.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.