Jump to content

[SOLVED] Create var - put it in array - redefine var - echo the var


malikah

Recommended Posts

Hi, does anyone know where I'm going wrong here?

 

$name = "";
$email = "";
$subject = "";
$message = "";

$fieldVals = array($name, $email, $subject, $message);

foreach($fieldVals as $key => $val)
    $fieldVals[$key] = "abc";

echo $name;
echo $email;
echo $subject;
echo $message;

//output: <nothing> (I was hoping to see "abc" for each variable).

 

Cheers.

When you do

$fieldVals = array($name, $email, $subject, $message);

you're creating an array containing the values from $name, etc, not a series of array elements pointing to the original variables.

 

try

$fieldVals = array(&$name, &$email, &$subject, &$message);

 

The separate variables should be passed by reference into the array (currently, they're passed by value only).

 

// ...
$fieldVals = array(&$name, &$email, &$subject, &$message);
// ... 

 

Another alternative would be to use the compact/extract functions.

 

// ...
$fieldVals = compact('name', 'email', 'subject', 'message');

foreach($fieldVals as $key => $val)
    $fieldVals[$key] = "abc";

extract($fieldVals);
// ...

 

P.S. Mark beat me to it, grrr it takes far too long for me to type replies.  :-[

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.