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

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Perl's Encoding::FixLatin equivalent in PHP

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

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

How to fix: Warning: Visiting this site may harm your computer - domainameat.cc

Return multiple values from a function in PHP

Decrypting files using GnuPG (GPG) via PHP

Traversing Arrays Using list() and each() in PHP

GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP

A Tutorial on Timezones and Timestamps

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

Convert IP address to integer and back to IP address in PHP

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

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to return number of digits of an integer in PHP

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

Latest Articles (in PHP)