Skip to content

Instantly share code, notes, and snippets.

@lenivene
Last active March 16, 2019 15:47
Show Gist options
  • Save lenivene/34567a3ca940c5881cec1362481703a0 to your computer and use it in GitHub Desktop.
Save lenivene/34567a3ca940c5881cec1362481703a0 to your computer and use it in GitHub Desktop.
Checks if multiple keys exist in an array

Function PHP

Powered By | Lenivene

Essa função é interessante para verificar vários 'input' de formulário ao mesmo tempo.

/**
 * Todos nomes presente na array
 * é para verificar na requisição via $_POST (nesse exemplo).
 */
$el_form = array(
    'nome',
    'sobrenome',
    'assunto',
    'Mensagem'
)

if( ! array_keys_exist( $_POST, $el_form ) ) {
    echo "Preencha todos os elementos";
}
else{
    echo "Sucesso!";
}
<?php
/**
* Checks if multiple keys exist in an array
*
* @param array $array
* @param array|string $keys
*
* @author Lenivene Bezerra
* @return bool
*/
function array_keys_exist( array $array, $keys ) {
$count = 0;
if( ! is_array( $keys ) ){
$keys = func_get_args();
array_shift( $keys );
}
foreach( $keys as $key ){
if( isset( $array[ $key ] ) || array_key_exists( $key, $array ) ) {
$count ++;
}
}
return count( $keys ) === $count;
}
// Secound option
function array_keys_exist( array $array, $keys ){
if ( ! is_array( $keys ) ) {
$keys = func_get_args();
array_shift( $keys );
}
foreach ( $keys as $key ) {
if( ! isset( $array[ $key ] ) || ! array_key_exists( $key, $array ) ) {
return false;
break;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment