-1

Let's say I have a php array like this:

$compare  = array("Testing", "Bar");
$my_array = array(
                "Foo=7654", "Bar=4.4829", "Testing=123" 
        );

So it's safe to say below:

$compare[0] = "Testing"  

So I wanna check if $my_array contains $compare[0] (in above case, yes it does) And if it contains returns that value from $my_array which is Testing=123

How's that possible?

FreshPro
  • 875
  • 3
  • 14
  • 35
  • 4
    Why not make the array like this: `$my_array = ['Foo' => '7654', 'Bar' => '4.4829', 'Testing' => '123'];` because it would make finding the result very easy: `echo $my_array['Testing'];` – KIKO Software Jan 25 '18 at 12:01
  • I agree, but $my_array is coming from an API so I cannot change the content – FreshPro Jan 25 '18 at 12:03
  • So what does the api return exactly? – jeroen Jan 25 '18 at 12:04
  • API's should NOT return data in such a format. You can convert it, like this: `parse_str(implode('&',$my_array),$better_array);` This might not work if the API puts weird things in the array, so be careful. – KIKO Software Jan 25 '18 at 12:05
  • Do you have to cater for things like `$compare=array("Testing", "Test", "Bar", "Fo");` as just looking for 'Test' will find 'Testing'. – Nigel Ren Jan 25 '18 at 12:11
  • 2
    @FreshPro An api does not return a php array, you seem to have parsed the returned data already. So depending on what it looked like, you could improve there to make further processing easier. – jeroen Jan 25 '18 at 12:12
  • Possible duplicate of [Search multidimensional array for value and return new array](https://stackoverflow.com/questions/18454390/search-multidimensional-array-for-value-and-return-new-array) – Neo Morina Jan 25 '18 at 12:14

2 Answers2

1

You may use foreach loop:

$result = array();
foreach ($compare as $comp) {
    foreach ($my_array as $my) {
        if (strpos($my, $comp) !== false) {
            $result[] = $comp;
        }
    }
}

in array $result is result of search

or by other way:

$result = array();
foreach ($compare as $comp) {
    foreach ($my_array as $my) {
        if ($comp = explode('=', $my)[0]) {
            $result[] = $comp;
        }
    }
}
Vladimir
  • 1,373
  • 8
  • 12
1

To use a single loop...

$compare  = array("Testing", "Bar");
$my_array = array(
    "Foo=7654", "Bar=4.4829", "Testing=123"
);
$output = [];

foreach ( $my_array as $element )   {
    if ( in_array(explode('=', $element)[0], $compare)){
        $output[] = $element;
    }
}
print_r($output);

This just checks that the first part of the value (before the =) is in the $compare array.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55