Alexander Bazikalo
Alexander Bazikalo

Reputation: 1

php search data in array

Need your help in finding the problem .the program will look for data in the array and display the name if there is a match ,the program does not work correctly ,locking for data only in the first array.

<?php
$result = '';
$birthdays = array(
    array("Alex",5,12),
    array("Tom",2,20),
    array("Sarah",6,12),
    array("Anna",6,8),
    array("Jonh",10,7)
);
if(isset($_POST)){
    $d = isset($_POST['day_bd']) ? $_POST['day_bd'] : '';
    $m = isset($_POST['month_bd']) ? $_POST['month_bd'] : '';

    $result = getBirthdayNameByDate($birthdays, $d, $m);

    $result = $result ? $result : 'no results found';
}
 function getBirthdayNameByDate($birthdaysArray, $day, $month){
    foreach($birthdaysArray as $array){
        if($array[1] == $month && $array[2] == $day){
            return $array[0];
        }
        return null;
    }
}
?>
<!DOCTYPE HTML>
<html> 
    <head>
        <style type="text/css">
        form{
            text-align: center;
        }
        input{
            width: 50%;
            margin-bottom: 20px;
            line-height: 30px;
            font-size: 25px;
        }
        .nameOut{
            text-align: center;
            margin-top: 40px;
            border:4px solid darkred;
            border-radius: 15px;
            font-size: 2em;
            text-transform: uppercase;
        }
        </style>
    </head>
    <body>
        <form action =""method ="POST">
            <label for="user_day">Day:
                    <input id="user_day" type="number" name="day_bd">
            </label>
            <br>
            <label for="user_month">Month:
                <input id="user_month" type="number" name="month_bd">
            </label>
            <br>
            <input type="submit">
        </form>
        <?php if($result){ ?>
        <div class="nameOut">
            <?php
            echo $result
            ?>
        </div>
        <?php } ?>
</body>
</html>

Upvotes: 0

Views: 52

Answers (1)

daxro
daxro

Reputation: 191

Move down your return null; one step.

function getBirthdayNameByDate($birthdaysArray, $day, $month){
    foreach($birthdaysArray as $array){
        if($array[1] == $month && $array[2] == $day){
            return $array[0];
        }     
    }
    return null;
}

But please note that your program only will return the first match. Consider storing the results in an array, so no birthday ppl are left out!

Upvotes: 1

Related Questions