is it somehow possible to pass an an array to a function like this example function:
send_mail($adress, $data)
{
return $data[0];
}
?
So could the input variable be an array? If yes, could someone show me an example, please?
is it somehow possible to pass an an array to a function like this example function:
send_mail($adress, $data)
{
return $data[0];
}
?
So could the input variable be an array? If yes, could someone show me an example, please?
是否有可能将数组传递给示例中的函数?
是的,将一个函数传递给你send_mail
是非常好的。但是[0]
您在函数内部进行的访问有点危险:
send_mail($adress, $data)
{
return $data[0];
}
如果$data
是一个空数组怎么办?您应该检查第一个元素是否存在( with(count($data) > 0)
或任何其他等价物),然后才使用它。
PHP 中还有一个小东西叫做类型提示,它会强制用户send_mail
使用数组变量,否则会触发 PHP 错误:
send_mail($adress, array $data) { ... }
你应该尽可能地使用它,以获得更健壮的代码。
You can pass an array to a function, and return an array from a function. By default, arrays are passed by value (a scalar), meaning that it is a copy of the array, and changes within the function do not affect the original array.
In the code that follows the first function call doesn't affect the content of the tempArray. In the second function call, that is passed by reference using the ampersand (&), the original array is changed.
$tempArray = array();
$tempArray[] = "hello";
function testFn($theArray) {
$theArray[] = "there";
return $theArray;
}
$result = testFn($tempArray);
echo print_r($result); // hello, there
echo print_r($tempArray); // hello
function testFnRef(&$theArray) {
$theArray[] = "there";
return $theArray;
}
$result = testFnRef($tempArray);
echo print_r($result); // hello, there
echo print_r($tempArray); // hello, there
不确定这是否是您要询问的内容,但您可以使用以下命令访问所有参数:http: //php.net/manual/en/function.func-get-args.php
这样您就可以将任意数量的参数传递给您的函数并从 func_get_arg 中获取它们。
这是你要问的吗?
将数组传递给函数
function addall($array_var){
<do something using the array $array_var>
}
$array_var=array(1,2,3,4);
addall($array_var);
从函数返回数组
function addall($i,$j,$k,$l){
$array_var=array($i,$j,$k,$l);
return $array_var
}
$array_var=array(1,2,3,4);
addall(1,2,3,4);
PS:函数可以没有任何参数,每个参数可以是单个 var 或数组。