Php checks if an item exists through an array of sessions

How can I loop through a set of session arrays and check if $_session['items'][1][p_alt-variation-1] etc. $_session['items'][1][p_alt-variation-1] ? [p_alt-variant- {n}] elements are dynamic if a certain element has these additional modifications, so it can be no more than 1

print_r ($ _ SESSION ['elements'])

 Array ( [0] => Array ( [p_name] => Hovid PetSep [p_code] => 336910 [p_coverImg] => 14-1460428610-ulNvG.jpg [p_id] => 14 [p_price] => 24.50 [p_qty] => 2 ) [1] => Array ( [p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Tinted) [p_code] => 2102649 [p_coverImg] => 12-1460446199-wI5qx.png [p_id] => 12 [p_price] => 68.00 [p_alt-variation-1] => Red [p_alt-variation-2] => L [p_qty] => 1 ) ) 

I want to show the user if a certain element has different options in their cart, if they exist, how to search for an element in an array if it contains a string like [p_alt-variant- {n}] through?

I use foreach($_SESSION['items'] as $cart_item){ ... } to combine all the cart items to display product information.

Thanks for the advice.

+5
source share
2 answers

Not a regular expression guru, but you can just get the keys and check with preg_grep . If there is more than one key for this keyword, simply count the results.

Here is an idea:

 foreach($_SESSION['items'] as $cart_item) { // loop the items $keys = array_keys($cart_item); // get the keys of the current batch // make the expression $matches = preg_grep('~^p_alt\-variation\-\d+~i', $keys); // simply just checking the key name with has a number in the end, adjust to your liking if(count($matches) > 1) { // if it has more than one, or just change this to how many do you want echo 'has more than one variation'; } } 

If you want to use some of these keys, simply use the results found inside $matches :

 if(count($matches) > 1) { foreach($matches as $matched_key) { echo $cart_item[$matched_key]; } } 
+2
source

Session variables, like any other array values; you can always use the isset function. Please contact: http://php.net/manual/en/function.isset.php

0
source

Source: https://habr.com/ru/post/1247324/


All Articles