Return multiple values from a function in PHP

By: Devinemke  

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.




Archived Comments


Most Viewed Articles (in PHP )

Function to return number of digits of an integer in PHP

All possible substrings in a String in PHP

Execution Lifetime of a PHP script

Polymorphism in PHP

Decrypting files using GnuPG (GPG) via PHP

Using class within a function in PHP

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

Function to sort array by elements and count of element in PHP

Malware: global $ob_starting;

Function to convert strings to strict booleans in PHP

PHP pages does not display in IIS 6 with Windows 2003

Latest Articles (in PHP)

Comment on this tutorial