检查数组是否具有三个值

时间:2011-09-28 09:48:37

标签: php arrays

如何检查从另一个文件传递给函数的数组(具有三个值)是否具有所有三个值? 例如,如果有人放入$ ids = Api_Books_Book :: getTest(array(1,2,)),我想得到一个错误; (第三个键/索引没有值)。

到目前为止这是我的代码

public static function getTest($ids){
        $input_result = array(
                      );

        foreach ($ids as $id) {
       $input_result['result']['Id '.$id] =  $id;
       }

            if((array_key_exists('0',$ids))){

            echo "You have inputted some data in the Api_Books_Book::getTest<br/>";
            $input_success = "Successful!";
        }
        else 
        {
            echo "There is no data<br/>";
            $input_success = "Not Successful";
        }

        $result=array('status'=>$input_success,
                      'message'=>"some errors will be displayed here",
                      'result'=> $input_result
                     );



        rdie($result);



                return $result;
}

1 个答案:

答案 0 :(得分:0)

如果你有简单的数字索引数组,唯一有意义的是count

if (count($array) != 3) // not valid

或:

if (count($array) < 3) // not valid

您可以使用$array = array_values($array)重置数字键,以确保值位于索引[0][1][2],而不是任何其他索引。

如果你有key =&gt;值对并且您希望设置某些键,请使用array_diff_key

$expectedKeys = array('foo', 'bar', 'baz');
if (array_diff_key(array_flip($expectedKeys), $array)) // not valid
相关问题