dtoaillwk759656786 2015-04-25 12:41
浏览 62

如何检查数组中是否存在给定的键或索引?

I have created an array of data from mysql database. This is how that array looks like:

// Fetch all the records:
while ($stmt->fetch()) {

    $output  =  "<a>
";
    $output .=      "<h3>{$product_name}</h3>
";
    $output .=      "<span class='price'><span class='amount'>BD.{$price}</span></span>
";
    $output .=  "</a>
";
    $output .=  "<div class='short_desc'>
";
    $output .=          "$product_des
";       
    $output .=  "</div>
";

    //Add output to array
    $products[] = $output;      
}

Since I want to use this array values from outside my while loop and This is how I use this $products[] array in my page.

echo $products[0];
echo $products[1];
echo $products[2];
echo $products[3];

My question is if this $products[] array have one result set I can get an error.

My error message is like this: An error occurred in script 'C:\wamp\www\Computer\index.php' on line 208: Undefined offset: 2

So I tried to fix this problem using array_key_exists() function like this way for each echo:

if(!empty($products) && array_key_exists("$products[1]", $products)) echo $products[1]; else echo "No Product";

But still I can get error. Can anybody tell me what is wrong with this?

Thank you.

  • 写回答

3条回答 默认 最新

  • du3979 2015-04-25 12:58
    关注

    You probably want something like:

    if( ! empty($products) ) {
        $ids = array(0, 1, 2, 3, 4, 5);
        foreach ( $ids as $id ) { 
          if ( ! empty($products[$id]) ) echo $products[$id];
        }
    } else { 
       echo "No Product";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探