Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Implement Generators in PHP 7

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 668
    Comment on it

    A generator is the simple and an efficient way to write your code in the form of the iterator.

    PHP generators is the simple way to write your code that use the foreach loop to repeat your data set of array, without building that array in the memory, that can cause the memory limit exceed issue.

     

    In General terms, PHP generators makes improvement in performance and decreases the memory limit and makes your code clean.

     

    In generators we use the yield(The yield keyword returns data from a generator function.) before going on to the example lets first Understand What Yield is?:

     

    Yield is the core part of the generator function and its statement is used to return the output of the function. Although it does not stop the execution of the function, it provides the value of the code looping over the generator function and pauses the process of that function, for the time set of course.

     

    Now let's see the example, "how we can use the generator":

    <?php
    function numberRange($start, $limit, $step = 1) {
        if ($start < $limit) {
            if ($step <= 0) {
                return false;
            }
    
            for ($i = $start; $i <= $limit; $i += $step) {
                yield $i;
            }
        } else {
            if ($step >= 0) {
    	    return false;
            }
    
            for ($i = $start; $i >= $limit; $i += $step) {
                yield $i;
            }
        }
    }
    
    /*
     * Note that both range() and numberRange() result are the same
     */
    
    echo 'Predefined Function';
    foreach (range(1, 9, 2) as $value) {
        echo "$value ";
    }
    echo "\n";
    
    echo 'Generator function';
    foreach (numberRange(1, 9, 2) as $value) {
        echo "$value ";
    }

     

    In the above example the range function will take more memory rather from the numberRange function as the generators used has reduced the exhausted memory limit.

     

    How did you find the article? Feel free to share your thoughts and questions in the comments section below.

    How to Implement Generators in PHP 7

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: