I am trying to validate whether or not an array is listed in an array.
I am trying to add a product name and url to an session, the session will contain all the products visited by a visitor, but I don't want it to add the same product twice, hence the validation. So if the product is already in the array, I want it to do nothing, but if it doesn't already belong to the array, it needs to be added. This is as far as I got so far. The only issue seems to be the validation.
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
foreach($_SESSION['products'] as $each_item) {
while(list($key,$value)=each($each_item)) {
if($key == 'product' && $value == $products_name) {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
}
}
these are the errors I am getting
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10
found
So I just want to know how you can check if an array is already in an multivariate array. Or if there are any other alternatives to achieving what I want here.
Change:
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
to:
$_SESSION['products'] = array(array('product'=>$products_name,'url'=>$viewed_product_url));
so that you get a 2-dimensional array.
However, I think this is a poor data structure. You should make $_SESSION['products'] an associative array, whose key is the product name. So you add elements to it with:
$_SESSION['products'][$products_name] = $viewed_product_url;
and you find products with:
$found = isset($_SESSION['products'][$products_name]);
check with is_array like
if(is_array($_SESSION['products']))
and then you can go with foreach
is_array() function will help you..
http://php.net/manual/en/function.is-array.php
$each_item is not an array. That is the reason for the error.
Try this
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
if (in_array($viewed_product_url, $_SESSION['products'])) { {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
}
}
Related
Is there any elegant way to check if
$review['passenger'] has any $review['passenger']['*']?
Try with is_array(). It will check if it is an array or not -
if(is_array($review['passenger'])) {
// is an array
}
Or if you want to check if some key is present or not then -
if(array_key_exists('key', $review['passenger'])) { ... }
I believe Danius was using "['*']" to reference "one or more sub-arrays", instead of specifying it as "the" sub-array.
About his question, the only way to verify if a specific KEY of your array has sub-arrays is checking its sub-items, one by one, to identify if any one of them is an array.
It may not be "elegant", but it is definitively functional:
function has_array($arr) {
$has_array = false;
foreach ($arr as $item):
if (is_array($item)):
$has_array = true;
break;
endif;
endforeach;
return $has_array;
}
Simply call the function this way:
$result = has_array($review['passenger']);
I hope it helps.
You can use array_key_exists:
$array = array(
"passenger" => array(
"*" => "ok"
)
);
if(array_key_exists('*', $array['passenger'])){
echo "ok";
} else {
echo "not ok";
}
when i try use in_array function in php for the second time for same array variable i got the following error saying:
in_array() expects parameter 2 to be array, string given in
when i wrap the function in condition is_array, it returns false, i already print the variable using print_r and its showing array structure, here's the code:
$chosenCour = array();
$chosenServ = array();
foreach ($preferences as $preference) {
if(!in_array($preference['courier'],$chosenCour)){
$chosenCour[] = $preference['courier'];
}
if(!in_array($preference['courier_service'],$chosenServ)){
$chosenServ[]= $preference['courier_service'];
}
}
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour)){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}
Check the additional condition for non empty array
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour) && count($chosenCour) > 0){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}
I need to identify every instance where a value in one array (needle) occurs in another array (haystack). in_array() seems to be my best option, and the code below works perfectly until I need to use it on rows fetched from a db - it keeps appending values instead of setting them each time it's called.
While I can't actually use unset() in this situation, I was surprised to discover that even that didn't seem to resolve the problem.
UPDATE - Example of what's being returned
I temporarily changed the db values so that $needles has only value per row (in order to make it possible to sort through the values filling up my screen ;-))
False;
False; False; True;
False; False; True; False; True;
False; False; True; False; True; False; True;
False; False; True; False; True; False; True; False;
This works correctly
(I've posted a functional example here)
$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');
foreach ($needles as $needle) {
if (in_array($needle, $haystack) ) {
$Match = 'True';
}
else {
$Match = 'False';
}
}
This keeps appending values - Edited to reflect the code I'm using
$Customer_Categories_Arr = array('Casual','Trendy');
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$Product_Categories_Arr[]=$row["Taste_Category"];
// Use when column contains CSV
// $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));
foreach ($Product_Categories_Arr as $Product_Category_Arr) {
if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){
$Matches_Product_Category = "True";
} else {
$Matches_Product_Category = "False";
}
echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
}
}
}
It is not really clear what you are trying to do. But maybe this would help:
$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
$productCategoryRow = $row[ 'Taste_Category' ];
// If it is not working, try uncommenting the next line
// $productCategories = [];
$productCategories = explode( ',', trim( $productCategoryRow ));
$match = "False";
foreach( $productCategories as $productCategory ){
if( in_array( $productCategory, $customerCategories )){
$match = "True";
}
echo $match . ";";
}
}
}
This prints your result on the screen every time a loop is done. Is this what you mean?
If you want the second block of code to do what the first block of code (which works correctly) does, then the second block should look like this -
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$needle =$row["product_var"];
$Match = "False";
if (in_array($needle, $haystack)){
$Match = "True";
}
}
}
You don't need do use the foreach because that is replaced by the while loop in the second block.
I am going to try an solve this. I think the problem is with:
$needles[]=$row["product_var"];
I think this should be:
$needles=$row["product_var"];
The column "product_var" contains an CSV (as you mentioned), so I can make an example like this:
$csv = "jake;john;alex;kim";
An example with brackets ($needles[]):
for($i=0; $i<5; $i++) {
$needles[] = explode(";", $csv);
echo(count($needles).", ");
}
returns:
1, 2, 3, 4, 5,
edit (for more explaining):
if I use print_r I see the array expanding, exactly how it happens in your example:
step 1: it adds an array to $needles with values ('jake','john','alex','kim')
step 2: it adds an array to $needles, so it contains 2x the values ('jake','john','alex','kim')
step 3: it adds an array to $needles, so it contains 3x the values ('jake','john','alex','kim')
etc.
Now without the brackets ($needles):
for($i=0; $i<5; $i++) {
$needles = explode(";", $csv);
echo(count($needles).", ");
}
This returns:
4, 4, 4, 4, 4,
And every time the array simply contains the values ('jake','john','alex','kim') -which is what you want.
Could this explain the "expanding values"? (or am I just doing something really stupid which has nothing to do with your problem??)
edit:
If this is what is going wrong, then you are adding to an array, instead of only using the new array from $row["product_var"] (hope this makes any sense; it seems I am pretty bad at explaining what's happening).
How can I store/remove/get an array of objects in the PHP session?
I tried this for adding:
array_push($_SESSION['cart'], serialize($item));
and this for removing:
function removeitem ($item)
{
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ )
{
if ($item.id == $arrayCart[i].id)
$arrayCart.splice (i,0);
}
}
But it doesn't work!!
<?php
session_start();
$_SESSION['cart']=array();
$_SESSION['cart']['username'] = 'Admin';
$_SESSION['cart']['Password'] = '123';
.
.
.
?>
For Remove
<?php
session_start();
$_SESSION['cart']=array();
unset ( $_SESSION['cart']['username'] );
.
.
or use Custom Function to Remove...
.
?>
It's Work For Me...
if this code Report Errors Please Comment to Check this...
Please check PHP version
How has no one seen this:
for ($i=0; $i<$arrayCart.length; $++ ){ // <----- lol # $++
Make it $i++
You also need another 2 } to close your if() and for() statements so it's like this:
function removeitem ($item){
$arrayCart = $_SESSION['cart'] ;
for ($i=0; $i<$arrayCart.length; $++ ){
if ($item.id == $arrayCart[i].id){
$arrayCart.splice (i,0);
}
}
}
Have you tried using this?
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
$_SESSION['cart'][] = $item;
You don't need to serialize the item-variable - a Session can store pure Objects, as long as the max. session-size doesn't exceed.
If you want to remove Items from the cart, you should use index-Names - this allows you to find your items faster.
I would probably use something like this:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
function addItem($itemName){
if(!isset($_SESSION['cart'][$itemName])) {
$_SESSION['cart'][$itemName] = 1;
}else
$_SESSION['cart'][$itemName] ++;
}
}
function removeItem($itemName){
if(isset($_SESSION['cart'][$itemName])) {
if($_SESSION['cart'][$itemName] > 0) {
$_SESSION['cart'][$itemName] --;
}
}
}
function clearCart(){
unset($_SESSION['cart']);
}
In this case, the cart stores each item and its amount. Instead of $itemName, you could also use the item-ID from your database.
To get an item from the cart, you will need this function:
function getItemCount($itemName){
if(isset($_SESSION['cart'][$itemName])) {
return $_SESSION['cart'][$itemName];
}
return 0;
}
Try not pushing to array, because its probably not set yet, but to store to session, create new session var by:
$_SESSION['cart']=serialize($item);
to remove it:
unset($_SESSION['cart']);
EDIT:
Thanks to comments I realized that above code wouldn't store array in session. So, another short solution is to store to session var some JSON. Try this for a short test:
$tmp = array(1,2,3);
$_SESSION['cart']=json_encode($tmp);
print_r(json_decode($_SESSION['cart']));
If that array is associative, you shoud use for decode:
json_decode($_SESSION['cart'], true);
hmm i got a homework, its 2 hours and i still have no clue on it :|
like this
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
// here is the homework function
CheckSession('lefthand,righthand,head,cloth,pants');
we have some string "lefthand,righthand,head,cloth,pants"
question is : " how can we check if the five session is not null or exist and display which session is empty ( if there is an empty session ) if all exist then returns a true ?
empty righthand , pants, and cloth.
this is how i think about it
explode it to arrays
check one bye one if !null id there is a
here is the progress that ive made *edit4 , :)
function CheckSession($sessions){
$all_sessions_exist = true;
$keys = explode(',',$sessions);
$error = array();
// Search for Session that are not exist
foreach ($keys as $key) {
if (!isset($_SESSION[$key]) && empty($_SESSION[$key])) {
echo "no $key</br>";
$all_sessions_exist = false;
}
}
return $all_sessions_exist;
}
Thanks for taking a look
Adam Ramadhan
Seeing as it's homework, you won't get the solution. You're on the right track though. explode() it by the delimiter. You can the loop through it using foreach and use empty() to check if they're set. You can access the sessions like $_SESSION[$key]. Keep an array of the ones that match.
function CheckSession($string){
$all_sessions_exist = true; #this will change if one of the session keys does not exist
$keys = explode(',', $string); #get an array of session keys
foreach($keys as $key){
if(isset($_SESSION[$key])) {
if(!empty($_SESSION[$key]))
echo '$_SESSION['.$key.'] is set and contains "'.$_SESSION[$key].'".'; #existing non-empty session key
else echo '$_SESSION['.$key.'] is set and is empty.' ;
}else {
echo '$_SESSION['.$key.'] is not set.'; #key does not exist
$all_sessions_exist = false; #this will determine if all session exist
}
echo '<br />'; #formatting the output
}
return $all_sessions_exist;
}
Just cleaning up your function
function CheckSession($sessions)
{
$session = explode(',',$sessions);
$return = array();
foreach ($session as $s)
{
$return[$s] = (isset($_SESSION[$s]) && !empty($_SESSION[$s]) ? true : false)
}
return $return;
}
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
And the checking part
// here is the homework function
$Results = CheckSession('lefthand,righthand,head,cloth,pants');
Edit
//$value1= false; // Commented out so does not get set
$value2= false; //Still set to a bool
error_reporting(E_ALL);
empty($value1); // returns false but still strikes E_NOTICE ERROR
empty($value2); // returns false with no error
Note, empty does not trigger an error but this example would take affect an a lot of other php functions.