不能在 php 之外为 each 语句设置变量


Cant set variable outside of php foreach statment

我试图让$leadsource在foreach语句之外打印或回显,但它不起作用。

如果我像这样在foreach语句内部回显$leadsource www.test.com?id=2462它可以工作,但是如果我尝试在foreach语句之外回显$leadsource,这是我需要发生的,它会返回数组中的错误值。这让我发疯,任何人能给我的任何帮助,我将不胜感激。

$sourcetracking=$_GET['id'];
$LegacyIDLookupArray = array(
    '2612' => 'ADV-ShowProg',
    '2462' => 'ADV-ShowProg-3.5x7',
    '2422' => 'ADV-Mag-book'
    );

if (!empty($sourcetracking))
{
    foreach ($LegacyIDLookupArray as $LegacyID => $Oldleadsource)
    {
        if ($sourcetracking == $LegacyID)
        { 
            $leadsource = &$Oldleadsource;
            // echo "$leadsource'n"; Echoing $leadsource here works properly.             
        }        
    }
}
else
{
    echo "fail";
}
echo "$leadsource'n"; // echoing $leadsource here echo's the wrong one in the array.

试着休息一下。

// As a side note: you can check at the very beginning to see that
// the ID isn't being compromised by something by checking if 
// is_numeric. Also, you can save your 'fail' message until the very
// end when checking that your $leadsource isset. These extra points
// are not essential, but they will throw a fail at all points of the 
// code (if that is valuable at all to you)
$sourcetracking = (isset($_GET['id']) && is_numeric($_GET['id']))? $_GET['id']:false;
if($sourcetracking !== false) {
    $LegacyIDLookupArray = array(
        '2612' => 'ADV-ShowProg',
        '2462' => 'ADV-ShowProg-3.5x7',
        '2422' => 'ADV-Mag-book'
        );
         foreach ($LegacyIDLookupArray as $LegacyID => $Oldleadsource) { 
              if($sourcetracking == $LegacyID) { 
                   $leadsource = &$Oldleadsource;
                   // This is where the break goes to stop your loop
                   // when condition is met
                   break;            
               }
          }
    }
// Your $leadsource OR fail is echoed here.
echo (isset($leadsource))? $leadsource : "fail";
original code:
$sourcetracking=$_GET['id'];
$LegacyIDLookupArray = array(
    '2612' => 'ADV-ShowProg',
    '2462' => 'ADV-ShowProg-3.5x7',
    '2422' => 'ADV-Mag-book'
    );

if (!empty($sourcetracking)) {  
            foreach ($LegacyIDLookupArray as $LegacyID => $leadsource) { 
                    if($sourcetracking == $LegacyID) { 
                        $leadsource = $_POST['LeadSource'];
                        break;            
                    }
                }
}else {
    echo"fail";
}
// You may want to do a check to make sure it is set or you will
// get a variable not found error. Even if you think it should be
// set 100% of the time, you just never know. May as well put the 
// isset in.
if(isset($leadsource)) {
   echo $leadsource;
    }