Skip to content

Instantly share code, notes, and snippets.

@vsilva472
Last active December 10, 2018 17:47
Show Gist options
  • Save vsilva472/cd4f47b97909161e677fdd607457e333 to your computer and use it in GitHub Desktop.
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
<?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