5

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.

2 Answers 2

2

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];
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks...but I have another question in regards on after if(count($matches) > 1){ }, I wanted to loop through and echo `$cart_item['p_alt-variation-{n}'], how can I do that?
@Lisa8 you can just use foreach again inside the $matches
Thank you so much, what a useful help!!
@Lisa8 sure glad this help
0

The session variables are just like any other array values; you can always use isset function. Please refer: http://php.net/manual/en/function.isset.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.