-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?

7
  • 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']; Commented Jan 25, 2018 at 12:01
  • I agree, but $my_array is coming from an API so I cannot change the content Commented Jan 25, 2018 at 12:03
  • So what does the api return exactly? Commented Jan 25, 2018 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. Commented Jan 25, 2018 at 12:05
  • 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. Commented Jan 25, 2018 at 12:12

2 Answers 2

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Double foreach is ugly, and the if condition is wrong
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.