Azima Azima - 1 year ago 57
PHP Question

using header function inside a loop

<?php
$a = array('f-stat,porcelain mask'=>'jay azima','jay azima,oil painting'=>'japanese doll');
$msg="We can't recommend any items to you.";
foreach($a as $k=>$v)
{
if($_GET['items']==$k)
{
header("location: hola.php?tequilla=".$v);
}

}
header("location: hola.php?tequilla=".$msg);
?>


What I tried to do is if string from
$_GET['items']
matches any of key in
$a
array, it is redirected to hola.php with
$v
value. Otherwise
$msg string
is passed. But the problem is even if the
$k
and
$_GET['items']
matches, latter header function is executed with
$msg
value. Also if I remove the latter header function, the header function inside the loop works fine.

Answer Source

Use exit() it stops the execution of the script. This will not redirect to second header.

<?php
    $a = array('f-stat,porcelain mask'=>'jay azima','jay azima,oil painting'=>'japanese doll');
    $msg="We can't recommend any items to you.";

    foreach($a as $k=>$v)
    {

      if($_GET['items']==$k)
      {
        header("location: hola.php?tequilla=".$v);
        exit(); // < this will stop the script before the 2nd header()
      }

    }

    header("location: hola.php?tequilla=".$msg);
    exit();

    ?>