Tudor Manole Tudor Manole - 5 months ago 12
PHP Question

Echo only if it hasn't already been echoed?

What I'm trying to do is make a list of entries from a form, but I do not want the same entry to be displayed multiple times in the list if it was entered more than once in the form. For example, say one person enters "1" but then two people enter "2", I would only want the 2 to appear once in the list. What function would I be able to use for this?

Answer

In this case you should use PHP Arrays. Arrays are 2-dimensional tables.

/* Array
 * key => value
 * @key personID
 * @value optionValue
 */
$array = array(
    1 => 1, // Person 1 chose Option 1
    2 => 2, // Person 2 chose Option 2
    3 => 2  // Person 3 chose Option 2
);
print_r($array);

Prints

Array
(
    [1] => 1 
    [2] => 2 
    [3] => 2
)

You are now able to fetch a set of unique values by accessing the array via array_unique($array);.

$array_unique = array_unique($array);
$array_unique_values = array_values($array_unique);

// Access array values directly and store into variables.
// Notice that arrays in PHP start with the index zero.
$option1 = $array_unique_values[0];
$option2 = $array_unique_values[1];

echo "Option #1: " . $option1 . "\n";
echo "Option #2: " . $option2;

Prints

Option #1: 1
Option #2: 2

VoilĂ .

Comments