简体   繁体   中英

return result of foreach loop(s)

I have the some code which looks something like this (I've simplified it):

function process_something($a){
    foreach($a as $b){
        // Some logic here
        return $something;
    }
}
$input=[]; // An array of some kind
echo process_something($input);

I expect that final line to echo what the loops have returned but I get nothing. Maybe the above code will not work. I just put it in for illustration. I have a lot of nested loops working together to return various things.

If I have the loops echo data out, it works. However, I need this function to just return the end result to me for further processing, rather than echoing out to the user.

How do I proceed?

In this case this loop will only run once, because return jumps out of a function on the first occurrence.

It should be more like:

function process_something($a){
    foreach($a as $b){
        $something = 'Some math or other logic here';
    }
    return $something;
}
$input=[]; // An array of some kind
echo process_something($input);

Please post your code, we will try to figure out what's wrong with it.

This is the perfect case for a generator , a concept that I rarely seen used.

  function process_something($a){
    foreach($a as $b){
      // Some logic here
      yield $something;
    }
  }

  $input=[]; // An array of some kind

  /**
   * The generator returns an Iterator instance
   * so you'd need to loop over it
   */
  foreach(process_something($input) as $item){
    // do stuff here
    // echo $item
    // echo $item->something
    // your call
  }

The major advantage here is that you can "return without actually returning", you're yielding a value and the generator continues on with it's work.

Not to mention it's very memory efficient, altough 99% of the times memory is not an issue.

AND, this is the nice part, you can apply specific logic for each of the items in the $input without needing to do some weird hack-ish function.


Alternatives

  function process_something($a){
    $return = [];

    foreach($a as $b){
      // Some logic here
      $return[] = $something;
    }

    return $return;
  }

The only reason this answer isn't a comment is that it's very rare that I see a question that would legitimately benefit from a generator. This is one of them.


More on generators:

http://blog.ircmaxell.com/2012/07/what-generators-can-do-for-you.html

https://scotch.io/tutorials/understanding-php-generators

I did get you properly . But I think you are looking for the last value of the array . to do that just do it :

function process_something($a){
   $b = array_reverse ($a);
   return $b[0];
}
class StrHelper
{
    /**
     * Check for $string starts with $query
     * @param $string
     * @param $query
     * @return bool
     */
    public static function startsWith($string,$query){
        return substr($string, 0, strlen($query)) === $query;
    }
}

class ModelSearchHelper
{
    /**
     * filter  where $key of $data arr startsWith $modelName
     * @param string $modelName
     * @param array $data
     * @return array
     */
    public static function searchFor(string $modelName,array $data){
// this code do same
//        $out=[];
//        foreach ($data as $key=>$value){
//          if(StrHelper::startsWith($key,$modelName)){
//                $out[$key]=$value;
//            }
//        }
//        return $out;
// of this
        return array_filter($data,function ($value,$key) use ($modelName){
            return StrHelper::startsWith($key,$modelName);
        },ARRAY_FILTER_USE_BOTH );
    }
}

$test=[
    'limit'=>10,
    'offset'=>5,
    'customer.name'=>'Fox',
    'customer.address.street'=>'forest st.'
];


//filter where $key of $model startsWith $modelName
var_dump(ModelSearchHelper::searchFor('customer',$test));

result:

array(2) {
  ["customer.name"]=>
  string(3) "Fox"
  ["customer.address.street"]=>
  string(10) "forest st."
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM