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. 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); 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. 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. 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
Archived
This topic is now archived and is closed to further replies.