user9402741
user9402741

Reputation:

Outputing an array elements as variables inside a function's parameter

Let's say i have the following array, how do i outputting it as variables?

$required = array('fname', 'email','lname');

For example like so: $fname,$email,$lname

I want to output that array as a function parameter (with the exact order)

like so: $mymail=smtpmailer($to, [required array here]);

So somehow i only want to edit the array, which elemets will dynamically be parsed to the function's parameters as variables

Upvotes: 2

Views: 1040

Answers (4)

Rinsad Ahmed
Rinsad Ahmed

Reputation: 1933

If you want those text elements 'to','fname','lname' and 'email' are to become keys of an associative array alongside a value as in the below example you can use the 'extract' function as follows

$required = array('to'=>'[email protected]','fname'=>'Bob', 'email'=>'[email protected]','lname'=>'Martin');
extract($required);
$mymail=smtpmailer($to, $fname,$email,$lname);

Otherwise, if you have already defined the values somewhere on top for the variables $to, $fname, $email and $lname and you want to dynamically make those strings become variables and need passing to the function, you should use the eval function to convert each string dynamically to a variable and use call_user_func_array to dynamically pass those values as below

$required = array('to','fname', 'email','lname');
$inputar = array();
foreach($required as $el)
       array_push($inputar,eval('return $'. $el . ';'));
call_user_func_array("smtpmailer", $inputar);

Upvotes: 0

Jason Grim
Jason Grim

Reputation: 413

If the array doesn't have keys and is always in the same order you can use the language construct list.

For example:

$required = array('John', '[email protected]','Doe');
list($fname, $email, $lname) = $required;
$mymail = smtpmailer($to, $fname,$email,$lname);

Upvotes: 0

weirdan
weirdan

Reputation: 2632

Assuming you want to pass values stored in variables whose names are identified by elements in $required, it would be something like this (using recent enough PHP version).

$fname = "John"; 
$email = "[email protected]";
$lname = "Doe";

$mymail = smtpmailer($to, ...array_values(compact(...$required)));

If you, however, want to pass values from $required into the smtpmailer() function, then you want

$required = ["John", "[email protected]", "Doe"]; 
$mymail = smtpmailer($to, ...$required);

Upvotes: 1

Eyad Bereh
Eyad Bereh

Reputation: 1726

So you want to create dynamic variables.

Let's suppose that you're using an associative array:

$required = array(
    "fname" => "First name",
    "lname" => "Last name",
    "email" => "[email protected]"
);

Here's how to create $fname , $lname , $email variables:

foreach ($required as $key => $value) {
    ${$key} = $value;
}

Now you can refer to the variables with their names , for example:

echo $email; //Output [email protected]

Upvotes: 1

Related Questions