Find string in array of strings php

zuhairkareem / search_partial_string_array.php

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

/**
* First Method.
*/
function array_search_partial ( $ arr , $ keyword )
foreach ( $ arr as $ index => $ string )
if (strpos( $ string , $ keyword ) !== FALSE )
return $ index ;
>
>
$ array = [ ‘apple’ , ‘orange’ , ‘pineapple’ ];
// search
array_search_partial( $ array , ‘app’ );
/******************************************* BREAK *****************************************************/
/**
* Second Method.
*/
// $m_array contains matched elements of array.
$ m_array = preg_grep( ‘/^app\s.*/’ , $ array );
/******************************************* BREAK *****************************************************/
/**
* Third Method.
*/
$ results = array ();
foreach ( $ array as $ value )
if (strpos( $ value , ‘app’ ) !== false )
>
if ( empty( $ results ) )
else
/******************************************* BREAK *****************************************************/
/**
* Fourth Method.
*/
$ results = array_filter( $ array , function ( $ value )
return strpos( $ value , ‘app’ ) !== false ;
>);
/******************************************* BREAK *****************************************************/
/**
* Fifth Method.
*/
array_walk( $ arr , function ( $ item , $ key )
if (strpos( $ item , ‘green’ ) !== false )
echo ‘Found in: ‘ . $ item . ‘, with key: ‘ . $ key ;
>
>);
/******************************************* BREAK *****************************************************/
/**
* Approximate search ; Search almost equal — manual method — rough
*/
foreach ( $ arr as $ index => $ string )
// Split the string to char array.
$ keyword_array = str_split( $ keyword );
// Number of characters matched in City string.
$ no_char_matched = 0 ;
// Check if each char is present in the City.
foreach ( $ keyword_array as $ key => $ value )
if (stripos( $ string , $ value ) !== FALSE )
// Increment for each matched char.
$ no_char_matched ++;
>
>
// If the matched char no is more than previous attempts, then store it.
if ( $ no_char_matched > $ max_no_char_matched )
$ max_no_char_matched = $ no_char_matched ;
// store the city index.
$ result = $ index ;
>
>
/******************************************* BREAK *****************************************************/
/**
* Approximate search ; Search almost equal — manual method — recommended
*/
// input misspelled word
$ input = ‘carrrot’ ;
// array of words to check against
$ words = array ( ‘apple’ , ‘pineapple’ , ‘banana’ , ‘orange’ ,
‘radish’ , ‘carrot’ , ‘pea’ , ‘bean’ , ‘potato’ );
// no shortest distance found, yet
$ shortest = — 1 ;
// loop through words to find the closest
foreach ( $ words as $ word )
// calculate the distance between the input word,
// and the current word
$ lev = levenshtein( $ input , $ word );
// check for an exact match
if ( $ lev == 0 )
// closest word is this one (exact match)
$ closest = $ word ;
$ shortest = 0 ;
// break out of the loop; we’ve found an exact match
break ;
>
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ( $ lev <= $ shortest || $ shortest < 0 )
// set the closest match, and shortest distance
$ closest = $ word ;
$ shortest = $ lev ;
>
>
echo » Input word: $ input \n»;
if ( $ shortest == 0 )
echo » Exact match found: $ closest \n»;
> else
echo » Did you mean: $ closest ? \n»;
>
// http://php.net/manual/en/function.levenshtein.php

Источник

in_array

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .

Note:

Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.

Return Values

Returns true if needle is found in the array, false otherwise.

Examples

Example #1 in_array() example

$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Got mac» ;
>
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Example #2 in_array() with strict example

if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
>

if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
>
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ was found\n» ;
>

if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ was found\n» ;
>

if ( in_array ( ‘o’ , $a )) echo «‘o’ was found\n» ;
>
?>

The above example will output:

See Also

  • array_search() — Searches the array for a given value and returns the first corresponding key if successful
  • isset() — Determine if a variable is declared and is different than null
  • array_key_exists() — Checks if the given key or index exists in the array

User Contributed Notes 8 notes

Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.

The solution is to use the strict checking option.

$array = array(
‘egg’ => true ,
‘cheese’ => false ,
‘hair’ => 765 ,
‘goblins’ => null ,
‘ogres’ => ‘no ogres allowed in this array’
);

// Loose checking — return values are in comments

// First three make sense, last four do not

in_array ( null , $array ); // true
in_array ( false , $array ); // true
in_array ( 765 , $array ); // true
in_array ( 763 , $array ); // true
in_array ( ‘egg’ , $array ); // true
in_array ( ‘hhh’ , $array ); // true
in_array (array(), $array ); // true

in_array ( null , $array , true ); // true
in_array ( false , $array , true ); // true
in_array ( 765 , $array , true ); // true
in_array ( 763 , $array , true ); // false
in_array ( ‘egg’ , $array , true ); // false
in_array ( ‘hhh’ , $array , true ); // false
in_array (array(), $array , true ); // false

I got an unexpected behavior working with in_array. I’m using following code:

// .
$someId = getSomeId (); // it gets generated/fetched by another service, so I don’t know what value it will have. P.S.: it’s an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = [‘dataOne’, ‘dataTwo’];
if ( in_array ( $someId , $anyArray )) // do some work
>
// .
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what’s going on.

I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

$needle = array(
‘fruit’ => ‘banana’ , ‘vegetable’ => ‘carrot’
);

$haystack = array(
array( ‘vegetable’ => ‘carrot’ , ‘fruit’ => ‘banana’ ),
array( ‘fruit’ => ‘apple’ , ‘vegetable’ => ‘celery’ )
);

echo in_array ( $needle , $haystack , true ) ? ‘true’ : ‘false’ ;
// Output is ‘false’

echo in_array ( $needle , $haystack ) ? ‘true’ : ‘false’ ;
// Output is ‘true’

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.

I’d like to point out that, if you’re using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I’ve tested, the function works correctly:
if the array is filled with strings and you’re searching for a string;
if the array is filled with Enums and you’re searching for an Enum.

Here is a recursive in_array function:

$myNumbers = [
[ 1 , 2 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
];

$array = [
‘numbers’ => $myNumbers
];

// Let’s try to find number 7 within $array
$hasNumber = in_array ( 7 , $array , true ); // bool(false)
$hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)

function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
>

$isFound = false ;
if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
>

if ( $isFound === true ) return true ;
>
>

If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.

$slow = array( ‘apple’ , ‘banana’ , ‘orange’ );

if ( in_array ( ‘banana’ , $slow ))
print( ‘Found it!’ );

$fast = array( ‘apple’ => ‘apple’ , ‘banana’ => ‘banana’ , ‘orange’ => ‘orange’ );

if (isset( $fast [ ‘banana’ ]))
print( ‘Found it!’ );

Источник

Читайте также:  Microsoft word and java
Оцените статью