php – $_post variable foreach loop logic problem-ThrowExceptions

Exception or error:

This code should check the input if it’s found in the array, but it does not. It just works for the first index [0]

<?php
$array = array(
    "joe",
    "sarah",
    "jaison",
    "klai",
    "hanna"
);
if ($_POST){
    foreach($array as $value){
        echo $value;
        if($_POST["name"] == $value){
            echo "yeb,i know him !";
            break;
        } else {
            echo "i dont know him";
            break;
        }
    }
}
?>
<p>please enter a name</p>
<form method="post">
    <input name="name" type="text">
    <input type="submit" value="go!">
How to solve:

1.Use in_array() instead of foreach()

2.Directly check posted name is empty or not.

3.Remove break;

<?php
$array=array("joe","sarah","jaison","klai","hanna");
if(!empty($_POST['name'])){
    // add true as 3rd parameter to in_array if you want to check types as well
    if(in_array($_POST['name'] ,$array)){
        echo "yeb,i know him !";
    }else{
        echo "i dont know him";
    }
}
?>
<p>please enter a name</p>
<form method="post">
    <input name="name" type="text">
    <input type="submit" value="go!">

Sample output:- https://3v4l.org/VObsX AND https://3v4l.org/HWkU1

Answer:

You dont have to use a foreach loop here. There is a function in_array that checks if an value is present in an array. Look at this example:

$array = array("joe", "sarah", "jaison", "klai", "hanna");

if (isset($_POST['name'])) {
  if( in_array ($_POST["name"], $array) ) {
    echo "yeb,i know him !";
  } else {
    echo "i dont know him";
  }
}

?>
<p>please enter a name</p>
<form method="post">
  <input name="name" type="text">
  <input type="submit" value="go!">
</form>

Answer:

You can use in_array() function for it. Like this way:

$array=array("joe",
            "sarah",
            "jaison",
            "klai",
            "hanna");

if ($_POST){
    if(in_array( $_POST["name"], $array )){
        echo "yeb,i know him !";
    }
    else{
        echo "i dont know him";
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *