Programming Tutorials

(追記) (追記ここまで)

Return multiple values from a function in PHP

By: Devinemke in PHP Tutorials on 2011年10月28日 [フレーム]

A function can only return one value, but that value can be an array or other compound value. If you want to just define several variables into the global scope within your function you can do two things:

1. return an array from your function and then run the extract() function

$result_array = test ();
extract ($result_array);

2. Or you can just append the variables to the $GLOBALS array:

$array = array ('first' => 'john', 'middle' => 'q', 'last' => 'public');
function upper_case () {
global $array;
foreach ($array as $key => $value)
{
$GLOBALS[$key] = strtoupper ($value);
}
}
upper_case ();
echo "$first $middle $last";
// returns JOHN Q PUBLIC

In this second example you can create multiple values without necessarily returning anything from the function. This may be handy for applying several functions (stripslashes, trim, etc..) accross all elements of $_POST or $_GET and then having all of the newly cleaned up variables extracted out for you.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /