0

I have an array

$results = array(101, 102, 103, 104, 105)

I also have a input field where the user enters a number

<input type ="text" name="invoice" />

I put what the number that user enters in, into a variable

$id = $_POST['invoice']

How would I write an if statement to check to see if the number that user entered is in that array

I have tried doing in a for each loop

foreach($result as $value){
  if($value == $id){
    echo 'this';
  }else{
    continue;
  }

is there a better way of doing this?

0

6 Answers 6

13
    if (in_array($id, $results)) {
         // ...
    }

http://php.net/manual/en/function.in-array.php

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

1 Comment

How to make this not case-sensitive? Thanks.
4

Use in_array():

if (in_array($_POST['invoice'], $your_array)) {
    ... it's present
}

1 Comment

How to make this not case-sensitive? Thanks.
1

ok you can try this:

if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}

1 Comment

How to make this not case-sensitive? Thanks.
0

You can use in_array, like the others have suggested

if(in_array($id,$results)) {
  //do something

} else {
  $no_invoice = true;
}

but if you happen to want to use your array key for anything, you can kill two birds with one stone.

if($key = array_search($id,$results,true)) {
  echo 'You chose ' . $results[$key] . '<br />';
}

Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.

Comments

0

If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:

if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}

if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);

for($ac=0; $ac<$arr; $ac++){

if($r[$ac]==$anr[$ac]){
$res=$res+5;

}
}
echo $res;
}

Comments

-1

Not quite.

your way is good enough, it only needs to be corrected.

foreach($results as $value){ 
  if($value == $id){ 
    echo 'this'; 
    break;
  } 
}

is what you really wanted

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.