Array passing by PHP array

4

Save personal, I have the following function

exec($dia, $mes, $ano);

I would like to make a foreach to run it through an array basis. I passed as follows

$a=array("1,2,2016", "2,2,2016","3,2,2016");

foreach($a as $as){ exec($as) };

But it presents the error of the second argument onwards:

  

Missing argument

How can I pass these parameters?

    
asked by anonymous 17.03.2016 / 19:36

4 answers

3

As of PHP 5.6, you can use argument unpacking

function exec($dia, $mes, $ano){
    // faz algo
}

$as = [
    [1, 2, 2016], 
    [2, 2, 2016], 
    [3, 2, 2016],
];

foreach($as as $a){ 
  exec(...$a);
};
    
17.03.2016 / 19:51
3

The problem is called from the function, it must necessarily have 3 arguments, to pass they can transform this string into an array with explode() and pass each one individually.

$a = array("1,2,2016", "2,2,2016","3,2,2016");

foreach($a as $as){
    $param = explode(',', $as);
    exec($param[0], $param[1], $param[2]);
}

Another way to do

function nova(){
    list($d, $m, $y) =  explode(',',  func_get_args()[0]);
    echo "$d/$m/$y <br>";
}


$a=array("1,2,2016", "2,2,2016","3,2,2016");

foreach($a as $as){
    nova($as);
}
    
17.03.2016 / 19:45
2

Just to note, a variant of @rray's response:

$a = array(
   array( '1', '2', '2016' ),
   array( '2', '2', '2016' ),
   array( '3', '2', '2016' )
);

foreach($a as $as){
    exec( $as[0], $as[1], $as[2] );
}
    
17.03.2016 / 19:56
-3

As PHP is very "flexible" it even gives you the ability to do so:

$a = ["1,2,2016", "2,2,2016","3,2,2016"];

foreach($a as $as){
    eval('exec('.$as.');');
}
    
18.03.2016 / 03:02