简体   繁体   中英

I am displaying the values of a multidimensional array. The values are being displayed but i am getting a notice of Undefined offset

if($numrows>0)
{
    $i=0;
    while($i<count($result_page[$i]))         //This is line 68
    {
        echo "<tr>";
        echo "<td>".$result_page[$i]['product_id']."</td>";
        echo "<td>".$result_page[$i]['product_name']."</td>";
        echo "<td>".$result_page[$i]['product_price']."</td>";
        $i++;
    }
}

This is the notice:

Notice: Undefined offset: 10 in /home/jatin/web/www.exam.com/admin/productlist.php on line 68.

I am getting this notice because when the loop will be executed for the last time then $i will be incremented and it goes out of the length of the array.

Each time the number of elements in the 2nd dimension changes thus I have to use count function.

The notice occurs when the condition is checked for the last time, So all my elements are displayed but the notice occurs.

Please give an appropriate solution.

well i found one solution myself also which is not a good option but it also works fine...........use the @ operator like given below ---

while($i<count(@$result_page[$i]))

Answers given by B.Desai and thavaamm are better options though.

您还可以使用以下函数来抑制警告。

error_reporting(E_ERROR | E_PARSE);

You can check whether the array key is set or not then continue loop

if($numrows>0)
{
    $i=0;
    while(isset($result_page[$i]) && $i<count($result_page[$i])         //This is line 68
    {
        echo "<tr>";
        echo "<td>".$result_page[$i]['product_id']."</td>";
        echo "<td>".$result_page[$i]['product_name']."</td>";
        echo "<td>".$result_page[$i]['product_price']."</td>";
    }
}

Can you try below one.

if($numrows>0)
{
    foreach($result_page as $row)         
    {
        echo "<tr>";
        echo "<td>".$row['product_id']."</td>";
        echo "<td>".$row['product_name']."</td>";
        echo "<td>".$row['product_price']."</td>";
    }
}

Using the @ operator will suppress the notice. If only that is what you are looking for. Or you can also use this:

while(isset($result_page[$i]) && $i<count($result_page[$i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM