What is the difference between a generator and an array?

后端 未结 4 698
面向向阳花
面向向阳花 2021-01-31 15:35

Today the PHP team released the PHP 5.5.0 version, which includes support for generators. Reading the documentation, I noticed that it does exactly what it coul

4条回答
  •  不知归路
    2021-01-31 15:51

    An array has to contain each value that you're looping over before you start looping; a generator creates each value "on the fly" as it is requested, so a lot less memory;

    An array works with the values it contains, and has to be prepopulated with those values; a generator can create values according to special criteria to be used directly... e.g. a fibonnaci sequence, or letters from a non-A-Z alphabet (calculated by the UTF-8 numeric value) effectively allowing alphaRange('א','ת');

    EDIT

    function fibonacci($count) {
        $prev = 0;
        $current = 1;
    
        for ($i = 0; $i < $count; ++$i) {
            yield $prev;
            $next = $prev + $current;
            $prev = $current;
            $current = $next;
        }
    }
    
    foreach (fibonacci(48) as $i => $value) {
        echo $i , ' -> ' , $value, PHP_EOL;
    }
    

    EDIT

    Just for fun, here's a generator that will return the Hebrew alphabet as UTF-8 characters

    function hebrewAlphabet() {
        $utf8firstCharacter = 1488;
        $utf8lastCharacter = 1514;
        for ($character = $utf8firstCharacter; $character <= $utf8lastCharacter; ++$character) {
            yield html_entity_decode('&#'.$character.';', ENT_NOQUOTES, 'UTF-8');
        };
    }
    
    foreach(hebrewAlphabet() as $character) {
        echo $character, ' ';
    }
    

提交回复
热议问题