Last active
December 10, 2018 17:47
-
-
Save vsilva472/cd4f47b97909161e677fdd607457e333 to your computer and use it in GitHub Desktop.
PHP function to check if an array has a value that contains some string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @function array_contains | |
* A simple php function that returns an array value contains a given string. | |
* | |
* @param array $array | |
* @param string $findme | |
* | |
* @return empty array if none is found | array with original key => value preserved | |
*/ | |
function array_contains ( $array, $findme ) { | |
return array_filter($array, function ($val) use ( $findme ) { | |
return strpos( $val, $findme ) !== false; | |
}); | |
} | |
// Example | |
$fruits = array( 'Apple', 'Grape', 'Banana', 'Avocado' ); | |
$findme = 'nana'; | |
$result = array_contains( $fruits, $findme ); | |
var_dump( $result ); // array( 2 => 'Banana' ); | |
// if you want to reset index use array_values on $result; | |
$reseted_indexes = array_values( $result ); | |
var_dump( $reseted_indexes ); // // array( 0 => 'Banana' ); | |
// check if something was found | |
if ( count( $result ) ) { | |
// someting is found | |
} else { | |
// nothing found | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment