reset() expects parameter 1 to be array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

reset() expects parameter 1 to be array

Post by JakeJ »

I get the following error:

reset() expect parameter 1 to be array, string given in <file name>

Code: Select all

$tempnpertotal = mysql_query("SELECT * FROM tempnper ORDER BY nperi") 
         or die(mysql_error());
 
        $row = mysql_fetch_array($tempnpertotal);
 
$top = reset($row);
$bottom = end($row);
 
echo reset($top);
echo reset($bottom);
 
My array is loading properly, I get the expect output from: echo $row['nperi'] etc.

However, echo $row[0][0] gives me the wrong output while echo $row[0] gives me the correct output. What am I missing here. I have the feeling all of it is connected.

BTW - The above code example was taken from some other code kindly provided to me here. My goal is to get the first element in the first row of an array and the first element in the last row of an array (multidimensional of course).

Here's the example I'm working from:

Code: Select all

// Numeric
$array = array
(   0 => array
    (   0 => 'R'
    ,   1 => 'S'
    ,   2 => 'T'
    )
,   1 => array
    (   0 => 'U'
    ,   1 => 'V'
    ,   2 => 'W'
    )
,   2 => array
    (   0 => 'X'
    ,   1 => 'Y'
    ,   2 => 'Z'
    )
);
 
// Works with numeric arrays
echo $array[0][0]; // R
echo $array[count($array) - 1][0]; // X
 
// Associative
$array = array
(   'zero' => array
    (   'a' => 'R'
    ,   'b' => 'S'
    ,   'c' => 'T'
    )
,   'one' => array
    (   'a' => 'U'
    ,   'b' => 'V'
    ,   'c' => 'W'
    )
,   'two' => array
    (   'a' => 'X'
    ,   'b' => 'Y'
    ,   'c' => 'Z'
    )
);
 
// Works with numeric and associative arrays
$first = reset($array);
echo reset($first); // R
 
$last = end($array);
echo reset($last); // X
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: reset() expects parameter 1 to be array

Post by AbraCadaver »

Because $row is not a multi-dimensional array, so reset() and end() return the string value of those positions in the array and your next call with the echo passes that string. This will work:

Code: Select all

$top = reset($row);
$bottom = end($row);
  
echo $top;
echo $bottom;
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply