0

I know PHP has a lot of functions for arrays, but I am not sure which one to use know, or if custom function is needed.

I have a function that accepts arrays, and I would need those arrays passed as arguments to have certain keys. When an array is passed, I would need to check if the form of the arrays is proper, example:

<?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

Is there any way to do this? Thank you very much.

2
  • 1
    Array_intersect_key might be useful here. Commented Dec 29, 2013 at 21:16
  • Thank you, very simple solution. Commented Dec 29, 2013 at 21:17

3 Answers 3

3
  • array_intersect_key() as mario mentioned

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

    For PHP < 5.5.0: replace the IF construct with count(array_diff($template, $array)) == 0

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Just realized my answer and the second part of your answer is almost identical. :)
@AmalMurali I've fixed a bug in both code samples thanks to your answer! I was missing the array_keys parts.
0
if(array_intersect( array_keys($array), array_keys($template)) == array_keys($template)){
  // do your business
}

Comments

0

Use array_diff() and array_keys()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.