Skip to content

Instantly share code, notes, and snippets.

@alanef
Created February 11, 2020 15:12
Show Gist options
  • Select an option

  • Save alanef/055133016982b0cd6502e108db9e4089 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/055133016982b0cd6502e108db9e4089 to your computer and use it in GitHub Desktop.
check element of an array

rather than always using a combination of if ( issett($array['element']) && 'test' === $array['element'] ) { }

This function can be called

if ( 'test' === xzy_get_element(,$array, 'element', 'test' ) ) { }

or if a boolean just

if ( xzy_get_element(,$array, 'element' ) ) { } // if missing default is false

function could easily be extended to accept a santize key e.g. you use with $_POST arrays to ensure santisation

// note guard block style of early returns
function xyz_get_element( $array, $key, $default = false ) {
if ( ! is_array( $array ) ) { // this line is here just in case you are checking something that is not actually an array
return $array;
}
if ( array_key_exists( $key, $array ) ) { // uses array_key_exists rather than isset as isset would not give you NULL values - bit of an edge case but ...
return $array[ $key ];
}
return $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment