Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php check if element exist through session array

How can I loop through set of session array and check if $_session['items'][1][p_alt-variation-1] and so on, are exist? the [p_alt-variation-{n}] elements are dynamic if certain item has these add-on variations, so it could be as much as more than 1

print_r($_session['items'])

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 for user if certain item has various variations in their cart if exist, how to look for element in array if contains string like [p_alt-variation-{n}] through?

I use foreach($_SESSION['items'] as $cart_item){ ... } to loop all cart items to show item's info.

Thanks for advice.

like image 220
Lisa8 Avatar asked Oct 30 '22 05:10

Lisa8


1 Answers

Not a regex guru, but you could just get the keys and check using preg_grep. If it has more than one key for that keyword, just count the results.

Here's the 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 wanted to use some of that keys, just use the results that was found inside $matches:

if(count($matches) > 1) {
    foreach($matches as $matched_key) {
        echo $cart_item[$matched_key];
    }
}
like image 70
Kevin Avatar answered Nov 15 '22 07:11

Kevin