Webby
Webby

Reputation: 2765

PHP set multiple variables from a function

I am trying to set three variables from a test function.

Here's my code so far:

function test()
{
    $x = 1;
    $y = 2;
    $z = 3; 


}

test();

# should print '1', '2', and '3'
echo $x; 
echo $y;
echo $z;

Upvotes: 1

Views: 6885

Answers (5)

akond
akond

Reputation: 16035

function func ()
{
    return array (
        'x' => 1,
        'y' => 3,
        'z' => 42
    );
}


extract (func ());

echo $x, $y, $z;

or

function func ()
{
    return array (
         1,
         3,
         42
    );
}

list ($x, $y, $z) = func ();

Upvotes: 1

akira
akira

Reputation: 6117

options:

use references:

function test(&$x, &$y, &$z) {
    $x = 1;
    $y = 2;
    $z = 3;
}

or return an array and use extract:

function test() {
    return array(
        'x' => 1,
        'y' => 2,
        'z' => 3
    );
}

extract(test());

Upvotes: 2

RobinJ
RobinJ

Reputation: 5243

There'd be 3 easy-to-apply options in this case. One would be to pass the variables by reference, in stead of by value. The other would be to return an array. Another option would be to use global variables.
Here's an example of both:

By reference

<?php
function example (&$x, &$y, &$z)
{
    $x = 1;
    $y = 2;
    $z = 3;
}
?>

Passing a variable by reference means that you're passing the actual variable (the space allocated for it in the computer's memory), in stead of by value (just passing the value to the function) as usual.
So when you pass a variable by reference (which the & character does), and you manipulate the value, the value of the original variable gets changed as well.

Returning an array

<?php
function example ($x, $y, $z)
{
    $arr['x'] = 1;
    $arr['y'] = 2;
    $arr['z'] = 3;

    return $arr;
}
?>

Now you can access the values by using $arr['x'];, $arr['y']; and $arr['z'];.

Global variables

<?php
$x = 0;
$y = 0;
$z = 0;

function example ()
{
    global $x, $y, $z;

    $x = 1;
    $y = 2;
    $z = 3;
}
?>

Upvotes: 3

Michal
Michal

Reputation: 3368

Define the variables as global? Like:

function test()
{
    global $x, $y, $z;
    $x = 1;
    $y = 2;
    $z = 3; 
}

Upvotes: 1

Jakub
Jakub

Reputation: 20475

Just return an object or an array (array is probably the way to go):

function test(){
   $data = array(
     'x' => 1,
     'y' => 2,
     'z' => 3
   );

   return $data;

}

print_r( test() );

or call each value:

echo $data['x'];
...

Upvotes: 4

Related Questions