Home > Software design >  access to two global arrays?
access to two global arrays?

Time:10-21

How to access two global variables that store an array in themselves? I want to output two arrays at the same time.

It should be "12345" followed by "abcde"

$number = [1,2,3,4,5];
$str = ["a", "b", "c", "d", "e"];
 
 
function twoMassive(){
    $names = ["number", "str"];
  
    foreach($names as $items){
        yield $GLOBALS[$items];   // according to the plan, the elements of the $number 
                                // array should come out first, and then $str
    }
};
 
 
foreach(twoMassive() as $items){
    echo $items;
}

CodePudding user response:

You can use yield from to yield all values from your array:

<?php

$number = [1,2,3,4,5];
$str = ["a", "b", "c", "d", "e"];
 
 
function twoMassive(){
    $names = ["number", "str"];
  
    foreach($names as $items){
        yield from $GLOBALS[$items];   // according to the plan, the elements of the $number 
                                // array should come out first, and then $str
    }
};
 
 
foreach(twoMassive() as $items){
    echo $items;
}

Example

  •  Tags:  
  • php
  • Related