Skip to content

Instantly share code, notes, and snippets.

@Joel-James
Last active January 27, 2020 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joel-James/84d8039ebad70fe5ebd7a4445afd7663 to your computer and use it in GitHub Desktop.
Save Joel-James/84d8039ebad70fe5ebd7a4445afd7663 to your computer and use it in GitHub Desktop.
PHP - Partial string search in array
<?php
/**
* Helper function to do a partial search for string inside array.
*
* @param array $array Array of strings.
* @param string $keyword Keyword to search.
*
* @return array
*/
function array_partial_search( $array, $keyword ) {
$found = [];
// Loop through each item and check for a match.
foreach ( $array as $string ) {
// If found somewhere inside the string, add.
if ( strpos( $string, $keyword ) !== false ) {
$found[] = $string;
}
}
return $found;
}
// Simple list of fruits.
$fruits = [ 'apple', 'grapes', 'orange', 'pineapple' ];
// Result - [ 'apple', 'grapes', 'pineapple' ];
$found = array_partial_search( $fruits, 'ap' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment