0

I need to find the key and the value from an array that contains a specific letter without using the loop.

for Eg

$animal= array('lion','elephant','tiger');

I need to fetch the key and value which contain 'io'

output :

0 - lion
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
sudeeshmj
  • 19
  • 2
  • 1
    `$animal= ('lion','elephant','tiger');` isn't valid PHP. Did you mean `$animal= ['lion','elephant','tiger'];` perhaps? If so, then this is not a new problem - see https://stackoverflow.com/questions/15944824/search-a-php-array-for-partial-string-match (and several others) – ADyson May 17 '21 at 09:09
  • 1
    In general, you can't search in a list without using a loop. Even if it is not visible in *plain sight*, somewhere in the process a loop will be involved. – Yoshi May 17 '21 at 11:11

3 Answers3

0

use array_walk function. this function will apply user-defined callback function to each element of the array

$animal= ['lion','elephant','tiger','lions'];

array_walk($animal, function($value, $key) use (&$array)
{
        if(strpos($value,'io') !== false)
        $array[$key]= $value;
});

var_dump($array);

it give output:

Array ( 
[0] => lion 
[3] => lions )
Artier
  • 1,648
  • 2
  • 8
  • 22
  • Sorry, but if there is an `animal` start with `io` it will not be stored in `$array`, since the `strpost` return the first occurrence of that char in string which is `0`, and we know `if(0)` will not be executed. So just add `!== false`. could you see my answer! – XMehdi01 May 17 '21 at 13:24
0

You can use array_filter with option ARRAY_FILTER_USE_BOTH

$animal = array('lion','elephant','tiger');
$search = 'io';
$res = array_filter($animal, function($v, $k) use($search){
  return strpos($v, $search);
}, ARRAY_FILTER_USE_BOTH);
echo '<pre>';
print_r($res);

Working example :- https://3v4l.org/bdDSF

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
  • Same notice, I gave to @Artier, please do a test for `strpos($v, $search) !== false`, to include if there is an *animal* start with `io`. – XMehdi01 May 17 '21 at 13:27
0

loop over array with foreach and use a test strpos($value, $search) !== false, Which means $search exist in $value, So take position of it which is $key with its value, store them in $array. or just show them immediately (uncomment the echo line).

$animal = array('lion','elephant','tiger','ions');
$array = [];
$search = 'io';
foreach ($animal as $key => $value) {
    if(strpos($value, $search) !== false){
        $array[$key] = $value;
        //echo $key." - ".$value."<br>";
    }
}

Results:

foreach ($array as $key => $value) {
    echo $key." - ".$value."<br>";
}

Output:

/*
0 - lion
3 - ions
*/
XMehdi01
  • 5,538
  • 2
  • 10
  • 34