-1

I'm trying to understand the difference between array push and assign a value to the array with the equal sign in a foreach loop.

Here's my problem:

$data['database'] = array();

        if ($sql->num_rows() > 0)
        {
            foreach($sql->result_array() as $row)
            {   
                $data['database'] = $row;
                // array_push($data['database'], $row);
                var_dump($data['database']);
            }
        }

        die();

Let's pretend that before that I did a database query, something in the line of that: $sql = ee()->db->select('*')->from('exp_credit_tracker_assoc')->get(); since I'm using expressionengine, but really any prepared statement is good.

Now, if I use the comment statement

array_push($data['database'], $row);

It actually pushes my value to my array $data['database'], so when I dump my array outside of my foreach loop I can see all values.

Instead of, if I only assign the value:

$data['database'] = $row;

I can only see the array inside my loop, and, if I dump my array outside my loop, I can only see my first row. Which is very strange because I have a similar loop somewhere in my code, which does exactly the opposite, only assigning the value:

$sql = ee()->db->select('*')->from('exp_credit_tracker_credit_type')->get();

        $credit_type = array();

        foreach ($sql->result() as $row) {
            $credit_type[$row->credit_name]=$row->credit_name;
        }

I need to use the assignment syntax since I want to assign some values to some other variable on the fly, as soon as I make the query with MySQL, I was wondering if I'm making a mistake.

  • 1
    Check this note from the [array push documentation](http://php.net/manual/en/function.array-push.php): _"Note: If you use `array_push()` to add one element to the array, it's better to use `$array[] =` because in that way there is no overhead of calling a function."_ – Don't Panic May 11 '18 at 16:16

1 Answers1

3

If you want to use the assignment but see the same results as array_push() outside your loop, you need to assign the item as a new element in the array via:

$data['database'][] = $row;

This should produce the same results as:

array_push($data['database'], $row);

The way you have it written $data['database'] is being overwritten by $row.

War10ck
  • 12,387
  • 7
  • 41
  • 54