-2

I have:

if($tha==1||$tha==2||$tha==3...){
echo 'correct';
}

$tha is a value from 1 to 10000, randomly chosen.

If it is the same as one of the number to check against, then echo.

I have the numbers to check against stored in a array if needed called $thaArray. The count() on this array is 500.

Is there a way to make the if statement without typing all the elements I need to check against individually like above?

David19801
  • 11,214
  • 25
  • 84
  • 127

5 Answers5

1

in_array() will tell you whether a certain value can be found in an array.

$thaArray = array(1, 2, 3);
if (in_array($tha, $thaArray)) {
    ...
}

RTM Note:

Please try to familiarize yourself with the PHP manual. If you are working with an array, and you need a certain function, you have a great chance of finding it in the Array Functions page.

Other handy tools:

  • StackOverflow - with one search you could find hundreds of similar questions with the same answer(s)
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
kapa
  • 77,694
  • 21
  • 158
  • 175
1

Look at in_array:

if(in_array($tha, $thaArray)) echo 'correct';
steveo225
  • 11,394
  • 16
  • 62
  • 114
1

Put the numbers to check in an array and use in_array:

$primes = array(2, 3, 5, 7, 11, 13);
if (in_array($tha, $primes)) {
  echo 'correct';
}
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
0
$numbers = range(1,500);
if (in_array($tha, $numbers))
{
   echo 'correct';
}
matino
  • 17,199
  • 8
  • 49
  • 58
0

Yes, you should use the in_array() function. Your problem would be solved by:

<?php
if(in_array($tha, $thaArray)) {
    echo 'correct';
}
?>

That would do the desired..

stefandoorn
  • 1,032
  • 8
  • 12