繁体   English   中英

array_search错误的参数数据类型

[英]array_search wrong argument datatype

我正在玩这个:

$sort = array('t1','t2');

function test($e){
    echo array_search($e,$sort);
}

test('t1');

并得到这个错误:

Warning: array_search(): Wrong datatype for second argument on line 4

如果我不带这样的函数调用它,则结果为0;

echo array_search('t1',$sort);

这里出了什么问题? 感谢帮助。

PHP中的变量具有功能范围 变量$sort在函数test不可用,因为尚未传递它。您还必须将其作为参数传递给函数,或在函数内部定义。

您也可以使用global关键字,但实际上不建议这样做。 显式传递数据。

您必须将数组作为参数传递! 因为函数变量与php中的全局变量不同!

这是固定的:

$sort = array('t1','t2');

function test($e,$sort){
    echo array_search($e,$sort);
}

test('t2',$sort);

您不能直接从内部函数访问全局变量。 您有三种选择:

function test($e) {
  global $sort;

  echo array_search($e, $sort);
}

function test($e) {
  echo array_search($e, $GLOBALS['sort']);
}

function test($e, $sort) {
  echo array_search($e, $sort);
} // call with test('t1', $sort);

将$ sort放在函数内部,或将$ sort作为参数传递给函数test()。

例如

function test($e){
$sort = array('t1','t2');
    echo array_search($e,$sort);
}

test('t1');


----- OR -----
$sort = array('t1','t2');
function test($e,$sort){

    echo array_search($e,$sort);
}

test('t1',$sort);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM