php - 在 PHP 函数中访问单个数组变量

标签 php arrays callback

我有一个函数 userNumber($number),我想在其中返回两个变量。我知道在 PHP 函数中不可能返回多个变量,所以我创建了一个数组,这样我就可以在需要时访问数组中的任何索引/值。该函数测试用户的输入是否在 100 和 200 之间,并且应该输出数字的立方和平方根。

我想在变量中调用函数:

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

但我不知道如何访问每个变量中数组的每个值(比如调用索引的格式 - 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

同样,这是我想用返回值填充的两个变量(但不知道如何访问数组中的正方形或立方体以相应地填充变量):

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

任何有关如何访问函数中的各个数组值的输入,或有关了解更多信息的资源,我们都将不胜感激。

最佳答案

在您当前的实现中,您可以在 PHP >= 5.4.0 中执行此操作:

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

或者更好的是,这只会调用函数一次:

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

或者甚至更好,使用 list() 将数组值分配给各个变量:

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

上述方法也适用于以下返回的数组,但它可能更具描述性:

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

然后您可以使用 list() 或:

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

关于php - 在 PHP 函数中访问单个数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30516161/

相关文章:

php - 增量总数

php - 将选择框的选定值作为字符串发送到 PHP

javascript - 根据精确值重新排序数组

c# - 检查 C# BitArray 非零值的最快方法

c++ - 我怎样才能有效地使用 boost::progress_display 的回调?

php - Dockerfile php-fpm 未满足的依赖项

php - 在没有 Join 的情况下,在 3 个表中查找带有 field_in_set 的标签

python - 连续递增子序列

javascript - 根据 google places API 调用更新状态

javascript - 将大部分代码包装在回调函数中是 JS 中的常见做法吗?