2

I have an array like below:

$number = array(1,2,3,4,5);

I have a value like below:

$my_num = 2;

I want to compare $my_num variable in every $number array.

My expected output like this: No, Yes, No, No, No.

I tried like this:

<?php
if(in_array($my_num, $number))
{
    echo 'Yes';
}
else
{
    echo 'No';
}

But I can only get 'Yes' from above output.

How should I modify it in order to get my expected output?

1
  • 2
    you need a foreach loop Commented Sep 3, 2015 at 2:31

3 Answers 3

3

Like I said in the comment above, all you need is a foreach to iterate through your array and compare your data.

foreach($numbers as $num){
    echo ($num == $my_num) ? 'Yes' : 'No';
}

Source: http://php.net/manual/en/control-structures.foreach.php

Sign up to request clarification or add additional context in comments.

Comments

3

Here's one option, essentially comparing $my_num to each array value and mapping it to a Yes or No. The commas are for your expected result only.

$english = array_map(function($val) use ($my_num) {
    return ($val == $my_num) ? 'Yes' : 'No';
}, $number);
echo implode(', ', $english); // No, Yes, No, No, No

5 Comments

Agree mostly :) if you want to format it though (e.g. as the example with commas) then this method might save you having to built another array and implode that later
@Dagon I'll bet you say that to all your neighbours ;-)
Seems like someone's going around downvoting perfectly good answers, I got one at probably the same time. Lovely. Can you hear that "slithering" sound?
@Fred-ii- lucky he lives a few thousand km and an island away.
Appreciate the chat, but the comments probably aren't relevant unless you're using Google Maps API to determine them?
2

You can use a foreach loop. It loops through the array assigning the value of the current array member to the variable $num.

foreach ($number as $num) {
    if ($num == $my_num) {
        echo 'Yes';
    } else {
        echo 'No';
    }
}

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.