PHP arrays. inserting "$key" => "$value" pair into array with array_push();

Patrick picture Patrick · Dec 31, 2011 · Viewed 22.9k times · Source

Why won't this work?

$slidetotal=1;      
$slideids = array();
    while ($rowcs = mysql_fetch_array($orig_slides_result)) {
    $key = $slidetotal;
    array_push($slideids[$key], $rowcs['id']);
    $slidetotal++;
    }

I get this error: [phpBB Debug] PHP Notice: in file ///*.php on line 161: array_push() [function.array-push]: First argument should be an array

Although someone has commented you can do this on this page: http://php.net/manual/en/function.array-push.php , (find: "to insert a "$key" => "$value" pair into an array")

What is the next best way to insert a list of single values into a php array? By the way, I really can't believe it's hard to find something on this with google.com. Seriously?

Answer

Tim Cooper picture Tim Cooper · Dec 31, 2011

That PHP.net comment is incorrect. That is pushing $rowcs['id'] onto the array $slideids[$key], not the array $slideids.

You should be doing the following, in place of your array_push() call:

$slideids[$key] = $rowcs['id'];