Afan Pasalic wrote:
hi,
this one I can't figure out:
I have to assign value of an array to variable named after key of the
array several times in my project to , e.g. after I submit a form with
personal info I have
$_POST['name'] = 'john doe';
$_POST['address'] = '123 main st.';
$_POST['city'] = 'urbandale';
$_POST['zip'] = '12345';
$_POST['phone'] = '123-456-7980';
etc.
Then I assign value to the var name:
foreach ($_POST as $key => $value)
{
${$key} = $value;
}
and then validate submitted.
Though, to avoid writing all over again the same lines (even it's only 3
lines) I was thinking to create a function something like:
function value2var($array, $print=0)
{
foreach ($_POST as $key => $value)
{
${$key} = $value;
echo ($print ==1) ? $key.': '.$value.'<br>'; // to test
results and seeing array variables and values
}
}
value2var($_POST, 1);
but, I don't know how to get info from function back to script?!?!?
:-(
any help appreciated.
-afan
well, I would do something like this.
function value2var($in, $wanted=array(), $print=false) {
if ( ! is_array($wanted) ) {
$tmp = array($wanted);
} else {
if ( count($wanted) > 0 ) {
$tmp = $wanted;
} else {
$tmp = array_keys($in);
}
}
$myArr = array();
foreach ($tmp as $key) {
if ( isset($in[$key]) && !empty($in[$key]) ) {
$value = validate_data($in[$key], $key);
}
$value = '';
}
$myArr[$key] = $value;
// to test results and seeing array variables and values
if ( $print )
echo $key.': "'.$value.'"<br>';
}
}
return $myArr;
}
// Say $_POST looked like this
$_POST['first_name'] = 'John';
$_POST['last_name'] = 'Doe';
$_POST['address1'] = '123 Someplace Dr.';
$_POST['something_else'] = 'Some Value';
$wanted = array('first_name', 'last_name', 'address1');
extract(value2var($_POST, $wanted, TRUE), EXTR_SKIP, 'CLEAN');
// The EXTR_SKIP option will force extract not to create the variable if it already exists.
// Check out http://us2.php.net/extract for other options that could replace EXTR_SKIP
// After running the above line, you should end of with the variables that follow
echo $CLEAN_first_name; // This should echo John
echo $CLEAN_last_name; // This should echo Doe
echo $CLEAN_address1; // This should echo 123 Someplace Dr.
// and the something_else variable will not have been created as $CLEAN_something_else, because it
did not exist in the $wanted array
--
Enjoy,
Jim Lucas
Different eyes see different things. Different hearts beat on different strings. But there are times
for you and me when all such things agree.
- Rush
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php