Passing argument by PHP array

Asked

Viewed 158 times

4

Save everyone, I have the following function

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

would like to make a foreach to run it through a base in array. I passed the following way

$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 on:

Missing argument

how can I pass these parameters?

  • The problem is called from the function, need to obligatorily 3 arguments, if they are optional, put them in the signature as null

  • exact wanted each row of the array to represent the arguments, that 1 would refer to $dia, 2 $mes and 2016 $year on each line of the array.

4 answers

3

The problem is called from the function, need necessarily 3 arguments, to pass they can turn this string into an array with explode() and spend 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 of doing

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);
}
  • ah, I figured I’ll change and test here.... vlw even

3


From 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);
};
  • I was thinking that haha +1

2

For the record, a variant of the @rray 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] );
}

-3

As PHP is very "flexible" can even do so:

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

foreach($a as $as){
    eval('exec('.$as.');');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.