Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Merging FOREACH with IF : possible?? 2

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR
Hi,

I'm wondering if it possible to simplify the following code by giving FOREACH an ability to handle conditions by itself without having to use a sub IF statement as seen below :

Code:
foreach ($array as $key => $value) {

    if (strstr($value, "something")) {
    
    do_something();
    
    }

}

Thanks :)
 
Hi

Nope. But you can do the filtering before the looping if you use a function like this :
Code:
foreach ([url=http://php.net/preg_grep/]preg_grep[/url]('/something/',$array) as $key => $value) {
  do_something();
}
I would suggest to stay with your original code.

Feherke.
 
Hi

The perceivable effect depends on the size of the array, but generally is slower and uses more memory, because
[ul]
[li]with [tt]preg_grep()[/tt] you have to use regular expression even for the simplest substring search[/li]
[li][tt]preg_grep()[/tt] builds a new array on the fly[/li]
[/ul]


Feherke.
 
and you could always use array_walk instead of the foreach and then conditionalise the doSomething()

Code:
array_walk($array, 'doSomething');

function doSomething(&$value, $key){
  static $c =0;
  if ($value ==='something'){
     $value  = "something Else ($c)";
  }
  $c++;
}
 
Thanks jpadie :)

But unfortunately, I don't like the idea of creating a function for every condition.
 
you wouldn't be. your function is there already as per your first post (doSomething()). so instead you are adding the condition to the function that you are already creating.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top