Skip to content

Instantly share code, notes, and snippets.

@adelynx
Forked from kjbrum/search_for_value.php
Created August 17, 2019 22:20
Show Gist options
  • Save adelynx/af9d6ecc5b5926e2dcecee0cd8720c1d to your computer and use it in GitHub Desktop.
Save adelynx/af9d6ecc5b5926e2dcecee0cd8720c1d to your computer and use it in GitHub Desktop.
Check if a value exists in an array/object.
<?php
/**
* Check if an array is a multidimensional array.
*
* @param array $arr The array to check
* @return boolean Whether the the array is a multidimensional array or not
*/
function is_multi_array( $x ) {
if( count( array_filter( $x,'is_array' ) ) > 0 ) return true;
return false;
}
/**
* Convert an object to an array.
*
* @param array $object The object to convert
* @return array The converted array
*/
function object_to_array( $object ) {
if( !is_object( $object ) && !is_array( $object ) ) return $object;
return array_map( 'object_to_array', (array) $object );
}
/**
* Check if a value exists in the array/object.
*
* @param mixed $needle The value that you are searching for
* @param mixed $haystack The array/object to search
* @param boolean $strict Whether to use strict search or not
* @return boolean Whether the value was found or not
*/
function search_for_value( $needle, $haystack, $strict=true ) {
$haystack = object_to_array( $haystack );
if( is_array( $haystack ) ) {
if( is_multi_array( $haystack ) ) { // Multidimensional array
foreach( $haystack as $subhaystack ) {
if( search_for_value( $needle, $subhaystack, $strict ) ) {
return true;
}
}
} elseif( array_keys( $haystack ) !== range( 0, count( $haystack ) - 1 ) ) { // Associative array
foreach( $haystack as $key => $val ) {
if( $needle == $val && !$strict ) {
return true;
} elseif( $needle === $val && $strict ) {
return true;
}
}
return false;
} else { // Normal array
if( $needle == $haystack && !$strict ) {
return true;
} elseif( $needle === $haystack && $strict ) {
return true;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment