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.

Link to comment
Share on other sites

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);

 

Link to comment
Share on other sites

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.  :-[

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.