如何检查数组是否在PHP中需要键?

时间:2013-12-29 21:13:57

标签: php arrays compare

我知道PHP有许多数组函数,但我不确定使用哪一个,或者是否需要自定义函数。

我有一个接受数组的函数,我需要那些作为参数传递的数组才能拥有某些键。传递数组时,我需要检查数组的形式是否正确,例如:

<?php function( $array ) {
      // Array needs to have form Array('server'=>, 'database'=>,'username'=>
      I could check it as "array_key_exists", but it seems too long, there must be a
     a way to iterate throught arguments
     $template = Array('server'=>'', 'database'=>'','username'=>'');

     foreach( $array AS $key => $value ) {
       //Somehow compare if array $array includes keys as $template

有没有办法做到这一点?非常感谢你。

3 个答案:

答案 0 :(得分:3)

    正如马里奥所提到的
  • array_intersect_key()

    $template = array('server', 'database', 'username');
    if (array_intersect_key($template, array_keys($array)) == $template) {
      // all parameters were passed
    }
    
  • array_diff()

    $template = array('server', 'database', 'username');
    if (empty(array_diff($template, array_keys($array)))) { 
      // all parameters got passed
    }
    

    对于PHP&lt; 5.5.0:用count(array_diff($template, $array)) == 0

  • 替换IF构造

答案 1 :(得分:0)

if(array_intersect( array_keys($array), array_keys($template)) == array_keys($template)){
  // do your business
}

答案 2 :(得分:0)

使用array_diff()array_keys()

function check_keys(array $array) {
    $template = array('server', 'database', 'username');
    return (count(array_diff($template, array_keys($array))) == 0);
}