0
foreach ($arr as $k => $v){ foreach ($v as $e => $a){ if($a == 1){break;} //if $e has all 1's not just a single 1 (how to code it ?) } } 

how can I tell the first foreach function to break when $e has all 1's

Obviously this is not the actual code I'm using but its very similar, I need to walk through a two dimensional array and record the keys ($e) when their value ($a) is 1.

The above code finishes right after the first 1 : (

note: my array is not necessarily composed of numeric keys!

There maybe much better ways of tackling this problem.. any ideas?

Thank you so much!

example:

Array ( ["ny"] => Array ( [col0] => "" [col1] => "" [col2] => "" [col3] => "" [col4] => "" [col5] => "" ) ["chicago"] => Array ( [col0] => "1" [col1] => "1" [col2] => "1" [col3] => "1" [col4] => "1" [col5] => "1" ) ) 

I would like it to stop right after going through chicago.

2
  • Can you remove the break and add the value to a temp array instead? Commented Mar 25, 2011 at 18:36
  • You COULD try: array_unique($v) and check if it has 1 item with that specific value. Commented Mar 25, 2011 at 18:37

2 Answers 2

2
foreach ($arr as $k => $v){ if (count(array_diff($v, array(1))) == 0) { break; } } 
Sign up to request clarification or add additional context in comments.

3 Comments

You sneaky bastard, nice one and probably far more efficient than my method.
@Kevin - It's only a single count() on the subset of values, so it should be faster... though the array_diff() may be marginally slower than array_search() as array_search() will stop searching on the first match it finds
Thanks for reminding me that array_search doesn't solve this problem (needs to check if the array is completely 1's).
1

I'm not a 100% sure on what you want but would this fit your problem?

$totala = 10; $numa = 0; foreach ($arr as $k => $v){ foreach ($v as $e => $a){ if($a == 1){ $numa++; } if($numa == $totala) { break; } } } 

This way it will break when the amount of times 1 has been found is the same as you set the total to. (10 in this example.)

2 Comments

This actually could work, would it break the outer loop as well?
If you use break 2; it will. The 2 specifies that it has to break through 2 loops instead of just the deepest one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.