3

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?

Patrick
  • 241
  • 2
  • 8
  • 18
  • 1
    That comment is flat-out wrong. You cannot push a key-value pair onto an array with `array_push()`. – BoltClock Dec 31 '11 at 00:34
  • Before I tried the array_push(), I was doing what is supposedly correct according to Tim Cooper and osoner. – Patrick Dec 31 '11 at 03:35
  • Maybe I'm making the array correctly but not retrieving the variable from it correctly. Is this right? $id=$slideids[$i']; – Patrick Dec 31 '11 at 03:35

3 Answers3

6

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'];
  • That is exactly what I tried originally before looking it up. (Except I didn't redefine $slidetotal as $key) I'm not sure what went wrong except that I couldn't retrieve a variable from the array. – Patrick Dec 31 '11 at 03:25
  • Perhaps I'm not retrieving it correctly. Is this right? $id=$slideids[$id']; – Patrick Dec 31 '11 at 03:33
0

Why don't you do;

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

Also you can do like below if you don't need the key to start from 1;

$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
    $slideids[] = $rowcs['id'];
}
osoner
  • 2,425
  • 1
  • 15
  • 13
0

ummm hard-searching will work for google I think :) anyway, error tells you everything you need to know. that means first argument of array_push is not an array, you give a single value (string) to array_push ($slideids[$key]). Also why do you need to use array_push in php? I'd rather use

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

and what you're trying to do is:

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

i guess...

Mr. BeatMasta
  • 1,265
  • 10
  • 10