user4592091
user4592091

Reputation:

Accessing Individual Array Variables in PHP Function

I have a function userNumber($number) where I want to return two variables. I know it's not possible to return more than one variable in PHP functions, so I created an array so I can access any index/value from the array when needed. The function tests if the user's input is between 100 & 200, and should output the cube and square root of the number.

I want to call the function in variables:

$calculationSquare = userNumber($number);
$calculationCube = userNumer($number);

But I do not see how I can access each value of the array in each variable(like the formatting of calling an index - array[]);

Here is the function that converts the number into square/cube and returns the value via array:

function userNumber($number) {

    $square = "";
    $cubed = "";

if(100 < $number && $number < 200) {

$sqaure = sqrt($number);
$cubed = $number * $number * $number;

return array($square, $cubed);

} // end if

else {

       return false;
    } // end else
} // end function userNumber

Again, here are the two variables that I'd like to populate with the return values (but don't know how to access he square or cube in the array to populate the variables accordingly):

$calculationSquare = userNumber($number);
$calculationCube = userNumber($number);

Any input on how to access the individual array values in the function would be appreciated, or resources on learning more about this.

Upvotes: 5

Views: 101

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

In your current implementation you can do this in PHP >= 5.4.0:

$calculationSquare = userNumber($number)[0];
$calculationCube = userNumber($number)[1];

Or better, this would only call the function once:

$result = userNumber($number);
$calculationSquare = $result[0];
$calculationCube = $result[1];

Or maybe even better, use list() to assign array values to individual variables:

list($calculationSquare, $calculationCube) = userNumber($number);

The above approaches would also work with the following returned array, but it may be more descriptive:

return array('square' => $square, 'cube' => $cubed);

You can then use list() or:

$calculationSquare = $result['square'];
$calculationCube = $result['cube'];

Upvotes: 2

Related Questions