I am attempting to identify whether a variable in an array is present, and if it is state that it is “true” and if it is not state that it is “false”. The problem is that I am receiveing a response for all array variables, when I only want to know if the page variable is present in the array with link like http://example.com/product.php?image_id=50
<?php
$page = $_GET['image_id'];
if (!empty($_SESSION)){
foreach($_SESSION as $name => $value2) {
if (substr($name, 0, 7)=='images_') {
$id = substr($name, 7, (strlen($name)-7));
$get = mysql_query('SELECT * FROM images WHERE image_id='.mysql_real_escape_string((int)$id));
while ($cart_info_row = mysql_fetch_assoc($get)) {
$cart = array('image_id' => $cart_info_row['image_id'],);
if (in_array($page, $cart)){echo 'true';} else {echo 'false';}
}
}
}
}
}
?>
Assuming the numbers below are in the SESSION print_r ($cart):
Array ( [image_id] => 42 ) false
Array ( [image_id] => 45 ) false
Array ( [image_id] => 50 ) true
Array ( [image_id] => 49 ) false
Now, how can I ONLY identify if variable 50 ($page = $_GET['image_id'];)is present with out the other three?
As I understand, your code does 2 things: 1 – checks if key
images_$pageexists in session and 2 – checks if image withimage_id=$pageexists in database.Here
issetis used to check if the keyimages_$pageexists in$_SESSION. It is faster than making 2 calls tosubstr()function.Also, since we need only checking if given image exists,
foreachloop is replaced withif.After that, a MySQL query runs, and since we need only first match,
LIMIT 1is added to make query faster. Also comparison with image_id is already included in query, so its enough to test if there are returned rows or not (that’s why originalwhileis replaced withif).