malikah Posted October 21, 2009 Share Posted October 21, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/178498-solved-create-var-put-it-in-array-redefine-var-echo-the-var/ Share on other sites More sharing options...
Mark Baker Posted October 21, 2009 Share Posted October 21, 2009 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); Quote Link to comment https://forums.phpfreaks.com/topic/178498-solved-create-var-put-it-in-array-redefine-var-echo-the-var/#findComment-941307 Share on other sites More sharing options...
salathe Posted October 21, 2009 Share Posted October 21, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/178498-solved-create-var-put-it-in-array-redefine-var-echo-the-var/#findComment-941314 Share on other sites More sharing options...
malikah Posted October 21, 2009 Author Share Posted October 21, 2009 Thanks to both of you - problem solved. Quote Link to comment https://forums.phpfreaks.com/topic/178498-solved-create-var-put-it-in-array-redefine-var-echo-the-var/#findComment-941317 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.