PHP从函数中获取数组值

PHP从函数中获取数组值,php,Php,我有以下功能: function telephoneNums($telephoneNum) { $telephoneNum = trim($telephoneNum); $telephoneNum = preg_replace("/[^0-9]/", '', $telephoneNum); if($telephoneNum !=8){ $errorMsg[] = 'The contact number must be exactly 8 charator

我有以下功能:

function telephoneNums($telephoneNum) {
    $telephoneNum = trim($telephoneNum);
    $telephoneNum = preg_replace("/[^0-9]/", '', $telephoneNum);

    if($telephoneNum !=8){
        $errorMsg[] = 'The contact number must be exactly 8 charators long';
    }


    return $telephoneNum;
    return array_values($errorMsg[]);
}
我正在设法返回$telephoneNum,但我没有设法返回$errorMsg[]-我收到以下错误
PHP致命错误:无法使用[]读取

我还尝试了
返回$errorMsg[]但是我仍然得到相同的错误

我怎样才能返回
$errorMsg[]

就像这样

return array_values($errorMsg);
在这一行前面还有
return
语句。请尝试立即返回。在您的情况下,在第一个return语句之后,它不会返回第二个值

也只需初始化
$errorMsg
如下

$errorMsg = array();

如果您的
如果
条件不满足,那么至少应该用空值或数组初始化它。

这样使用数组没有意义,只需使用
$errMsg
。如果它“必须”是数组,则分配给索引并使用索引读取,即
$errMsg[0]

加:第二次
返回
将永远无法到达

如果要同时返回这两个值,可以这样做:

$result['phoneNum'] = '1234';
$result['errMsg'] = 'Whatever';

return $result;
preg_replace()
如果主题参数是数组,则返回数组,否则返回字符串。并改用
preg_match

function telephoneNums($telephoneNum) {
    $telephoneNum = trim($telephoneNum);
    $telephoneNum = preg_match("/[^0-9]/", $telephoneNum);

    if($telephoneNum[0] !=8){
        $errorMsg[] = 'The contact number must be exactly 8 charators long';
    }


    return $telephoneNum;
}

你的逻辑有问题。我会试着重写

function telephoneNums($telephoneNum) {
//    $telephoneNum = trim($telephoneNum); // useless because of next line
    $telephoneNum = preg_replace("/[^0-9]/", '', $telephoneNum);

    $errorMsg = array(); // initialize
    if(strlen($telephoneNum) !=8){ // you need to check length but a value
        $errorMsg[] = 'The contact number must be exactly 8 charators long';
    }

    // you cannot return value twice. 
    if (!sizeof($errorMsg)) // You need to decide what value you want to return
       return $telephoneNum; 
    else
       return $errorMsg; // there is no reason to use array_values.
}
检查下面的解决方案

function telephoneNums($telephoneNum) {
    $telephoneNum = trim($telephoneNum);
    $telephoneNum = preg_replace("/[^0-9]/", '', $telephoneNum);
    $op=Array();
    $op['telephoneNum']=$telephoneNum;
    $op['errorMsg']='';
    if($telephoneNum !=8){
        $op['errorMsg']='The contact number must be exactly 8 charators long';
    }

    return $op;

}

$out_put = telephoneNums('12345');
echo $out_put['telephoneNum'];
echo $out_put['errorMsg'];

你为什么不使用回声?例如:
echo“联系人号码长度必须正好为8个字符”
$errorMsg[]='foo'
相当于
数组推送($errorMsg,'foo')。在向数组中添加项时,您仅使用空括号(
[]
)。我需要在函数外部输出$errorMsg[],因此您必须按照我在回答中提到的那样初始化它