Home > Back-end >  PHP - array_push(): Argument #1 ($array) cannot be passed by reference
PHP - array_push(): Argument #1 ($array) cannot be passed by reference

Time:12-11

I am trying to store new array into a empty array but I am getting array_push(): Argument #1 ($array) cannot be passed by reference error

Here is my code...

 $sites = tbl_site::get();
        $newData = array();
        foreach ($sites as $key => $site) {
            $site_id = $site->site_id;
           
            $notification_count =  10;
            $newData[] = array_push(
                array(
                    "data" => array($site),
                    "count" => $notification_count
                )
            );
        }
return $newData;

CodePudding user response:

Array_push is a function returning number of elements. It has two arguments, array to add to and then elements to add.

array_push($newData, ...element ...)

But as suggested at https://www.php.net/manual/en/function.array-push.php to add one element its better to use [].

$newData[]=...element...

CodePudding user response:

You're misunderstanding the php signature for array_push

int array_push( array &$array, mixed $var[, mixed $...] )

The array_push function returns the length of the array after the push. The correct use of array_push would be

$newData = [];
array_push($newData, [
     "data"  => array($site),
     "count" => $notification_count
]);

  • Related