PHP从函数中获取数组值

时间:2014-12-29 11:29:10

标签: php

我有以下功能:

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 Fatal error: Cannot use [] for reading

我也试过return $errorMsg[];,但我仍然遇到同样的错误。

如何返回$errorMsg[]

5 个答案:

答案 0 :(得分:1)

检查以下解决方案

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'];

答案 1 :(得分:0)

试试

return array_values($errorMsg);

你在此行之前也有return语句。请尝试立即返回。在第一个返回语句之后的情况下,它不会返回第二个值。

同样只需初始化$errorMsg

$errorMsg = array();

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

答案 2 :(得分:0)

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

加号:永远不会达到第二个return

如果你想要返回两个值,你可以这样做:

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

return $result;

答案 3 :(得分:0)

如果subject参数是数组,则

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;
}

答案 4 :(得分:0)

你的逻辑有些不对劲。我会尝试改写。

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.
}