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.
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";
}
The function array_key_exists()
has, according to the documentation, a signature of:
bool array_key_exists ( mixed $key , array $array )
That is to say: It will return bool
(TRUE
or FALSE
) if the $key
(index
, would be 1
through 5
in your case) exists in $array
.
Therefore, the accepted syntax for your case is:
array_key_exists(1, $products)
HOWEVER, perhaps more straight-forward would be the use of empty()
or isset()
, both of which will work in your situation as:
if (!empty($products[0])) echo $products[0];
// ...
if (!empty($products[5])) echo $products[5];
Or:
if (isset($products[0])) echo $products[0];
// ...
if (isset($products[5])) echo $products[5];
It would also be possible to do a loop, including HTML, and stay sane:
<!-- PRE-HTML -->
<?php if(!empty($products)) foreach((array) $products as $product) { ?>
<!-- Product-Specific PRE-HTML -->
<?php echo $product ?>
<!-- Product-Specific POST-HTML -->
<?php } /* End for loop */ ?>
<!-- POST-HTML -->
If you want to access a single index within your array, without getting a notice, you have to check, if the key exists.
You might use isset (http://php.net/manual/de/function.isset.php):
if(isset($products[0]))
{
echo "yes, the key 0 is set within $products";
}
If you want to take all the entries, within your array, use foreach.
foreach($products as $product)
{
echo $product;
}