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?

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

3 Answers 3

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'];
2
  • 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. Commented Dec 31, 2011 at 3:25
  • Perhaps I'm not retrieving it correctly. Is this right? $id=$slideids[$id']; Commented Dec 31, 2011 at 3: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'];
}
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.