1

I want the loop just to output once. Instead it outputs twice. Here is the code:

$results = mysql_query($query);
    while ($c = mysql_fetch_array($results)){
        $individualPostcode = explode(",", $c['postcode']);
        foreach($individualPostcode as $val){ 
            $val = trim($val); //Get rid of spaces
            if($val === $postcode){
                echo $c['url']."<br>";
            }
        }
    }
}

Here is the output:

http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield

I've tried taken out the foreach loop but I need to go through that array checking against a user input.

Here is the initialisation of $postcode:

$userInput = $_POST["input"];
if(strlen($userInput) < 4) 
    echo "User Input : ".$userInput."<br>";
else //Below gets the first three chars of the users string
    echo "User Input : $userInput<br>What is being used : ".mb_substr($userInput, 0, 3)."<br>";

$postcode = mb_substr($userInput, 0, 3);    

2 Answers2

1

mysql_fetch_array returns both an associative and index array for each of your returned results. The foreach loop is going to loop over both and output twice. Try using mysql_fetch_assoc()

http://php.net/manual/en/function.mysql-fetch-array.php

Better still, try moving to the mysqli class. It's faster and mysql is depricated.

http://php.net/manual/en/intro.mysqli.php

LeDoc
  • 935
  • 2
  • 12
  • 24
1

You can always create an array of the URL's to stop them from duplicating by checking if the url has been put into the array:

$results = mysql_query($query);
$urlsArr = array();
while ($c = mysql_fetch_array($results)){
    $individualPostcode = explode(",", $c['postcode']);
    foreach($individualPostcode as $val){ 
        $val = trim($val); //Get rid of spaces
        if($val === $postcode){
            if (!in_array($c['url'], $urlsArr)) echo $c['url']."<br>";
            $urlsArr[] = $c['url'];
        }
    }
}
Danny Broadbent
  • 1,199
  • 1
  • 9
  • 21