php - How to checks if the given key or index exists in the array? -
i have created array of data mysql database. how array looks like:
// fetch records: while ($stmt->fetch()) { $output = "<a>\n"; $output .= "<h3>{$product_name}</h3>\n"; $output .= "<span class='price'><span class='amount'>bd.{$price}</span></span>\n"; $output .= "</a>\n"; $output .= "<div class='short_desc'>\n"; $output .= "$product_des\n"; $output .= "</div>\n"; //add output array $products[] = $output; }
since want use array values outside while
loop , how use $products[]
array in page.
echo $products[0]; echo $products[1]; echo $products[2]; echo $products[3];
my question if $products[]
array have 1 result set can error.
my error message this: error occurred in script 'c:\wamp\www\computer\index.php' on line 208: undefined offset: 2
so tried fix problem using array_key_exists()
function way each echo:
if(!empty($products) && array_key_exists("$products[1]", $products)) echo $products[1]; else echo "no product";
but still can error. can tell me wrong this?
thank you.
you want like:
if( ! empty($products) ) { $ids = array(0, 1, 2, 3, 4, 5); foreach ( $ids $id ) { if ( ! empty($products[$id]) ) echo $products[$id]; } } else { echo "no product"; }
Comments
Post a Comment