views:

32

answers:

2

I have an array of arrays like this:

$cart = Array ( 
[0] => Array ( [TypeFlag] => S [qty] => 2 [denom] => 50  [totalPrice] =>  100 )
[1] => Array ( [TypeFlag] => V [qty] => 1 [denom] => 25  [totalPrice] => 25 ) 
[2] => Array ( [TypeFlag] => C [qty] => 1 [denom] => 25  [totalPrice] => 25 ) 
) 

Is there any way, short of looping through all of them and checking one at a time, to determine if the TypeFlag value for any of them is S?

A: 

Try this:

foreach($cart as $key => $value) {
    if ($value['TypeFlag'] == 'S') {
        return $key;
    }
}

This would return the key of the sub-array that has a TypeFlag value of S. However, this would stop after it finds the first sub-array that matches your search pattern. Not sure what your desired output is tho and how many results are expected. If you can provide more info, I can give you a more accurate example.

FreekOne
Still uses a loop though, unless the OP just wants to avoid looping every single level of nesting.
BoltClock
Ah, my bad. I read *sort of loop* instead of *s**h**ort of loop* o.O
FreekOne
@BoltClock's a Unicorn - yes, I was really just trying to avoid looping through every level. I don't even need to return the key; I'm just setting a boolean to true if any of them match. Although if there was some way to do it with no looping at all, that would be superfabulous, too.
EmmyS
@FreekOne - no problem - it still fulfills my desire to avoid looping through each nested array.
EmmyS
@EmmyS: glad to be of help, then ! :)
FreekOne
A: 

Given a function that returns the TypeFlag for each element of your array:

function get_type_flag($item) {
    return $item["TypeFlag"];
}

You could apply that function to each element in the array:

$typeflags = array_map("get_type_flag", $cart);

and see if S is in that array:

if (in_array("S", $typeflags)) {
    ...
}
Richard Fearn
I'll take a look at this one; I've never used array_map before.
EmmyS
I just want to point out (before anyone else does!) that this will still iterate through all the array elements, in order to pull out the `TypeFlag` for each one. This approach to testing for at least one `S` uses the functional style of programming, which can be a bit clearer than a hand-coded `for` loop, a flag (to indicate whether you've found an `S`) and a `break` (to stop iterating once an `S` is found).
Richard Fearn