Last active
January 27, 2020 12:33
-
-
Save Joel-James/84d8039ebad70fe5ebd7a4445afd7663 to your computer and use it in GitHub Desktop.
PHP - Partial string search in array
This file contains hidden or 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 | |
/** | |
* 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