1

I want to use an if statement that when it matches a string in the database, it prints out a message. But, in the database, if there is more than one count of the string then it prints it out multiple times. Does anyone know how to make sure it only prints once? Many thanks. My code is:

    if ($value == 'America') 
    {
    echo "Welcome";
    }
3
  • 2
    What is your data stucture? What query are you using to pull the data? Commented Feb 11, 2014 at 17:16
  • u should have to use distinct in ur query Commented Feb 11, 2014 at 17:19
  • Would the use of break; be suffice? Commented Feb 11, 2014 at 17:22

4 Answers 4

2

Based on the information you have given one solution would be:

welcome_displayed = false;
if (welcome_displayed and $value == 'America') 
{
    echo "Welcome";
    welcome_displayed = true;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I assume you're in a loop. If so, I would use the break construct:

<?php

$array = array('red', 'blue', 'yellow');

foreach ($array as $color) {
  if ($color == 'blue') {
    print "We found a match.";
    break;
  }
}

If you're simply trying to write a query that only gets 1 match, use the DISTINCT keyword or LIMIT the number of results, or something like that. If you update your question I can update my answer accordingly.

Comments

0

You can also combine any matches into an array and then use 'array_unique' to only get the distinct items.

// DEFAULTS 
$matched_items = array();
$values = array('Denver', 'ABQ', '1234', 'asdfa', 'America', 'osproqr', 'America', 'iowrenvoiw', 'America');

// LOOP THROUGH EACH VALUE AND COMPARE IT AGAINST THE NEEDLE
foreach ($values AS $value) {
    if ($value == 'America') {
        $matched_items[] = $value;
    }
}

// PRINT OUT ONLY THE UNIQUE ITEMS
print_r(array_unique($matched_items));

Comments

-1

Use SELECT DISTINCT on the columns you want to select.

sql="SELECT DISTINCT /*table column*/ FROM /*TABLE NAME*/ WHERE /*column name*/ = America "

This will select only one row WHERE a column = America.

7 Comments

this suggestion not answer
While that would indeed result in a single row in the set returned from the database, we don't know if that would remove other information required in the query.
DISTINCT used with any column value
@user3227914 you haven't provided enough information to confirm if this would work or not.
Yep DISTINCT did exactly what I wanted, thank you so much for help guys
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.