Scenario - you want to create a list with values from a database. You have a column called names but you only want unique names in the list - no duplicates. Let's take a look at an example array made from a database call.
$namearray = array("Ana", "Bill", "Claudette", "Ana", "Bill", "Claudette", "Danny", "Erika", "Fabian", "Grace", "Danny", "Erika", "Ana", "Bill", "Claudette", "Danny", "Erika", "Fabian", "Ana", "Bill", "Claudette", "Danny", "Erika", "Fabian", "Grace", "Fabian", "Grace", "Ana", "Bill", "Claudette", "Danny", "Erika", "Fabian", "Grace")
As you see we have lots of duplicate names. Luckily PHP has a built in function which removes duplicates from arrays.
array_unique($arraystring); so for our namearray we can do
$namearray = array_unique($namearray); and by using print_r($namearray); we can see what our array now looks like
Array ( [0] => Ana [1] => Bill [2] => Claudette [6] => Danny [7] => Erika [8] => Fabian [9] => Grace )
The problem comes when we try to use a for loop to populate the list. array_unique maintains the original key number (the value between [] ). Ideally we want our array to look like this
Array ( [0] => Ana [1] => Bill [2] => Claudette [3] => Danny [4] => Erika [5] => Fabian [6] => Grace )
if we try our for loop usingfor ($i=0;$i < count($namearray);$i++){
echo $namearray[$i]."<br>";
}
Ana
Bill
Claudette
Danny
Erica, Fabian and Grace are missing from the list
What we need to do before executing the for loop is renumber the array keys using :$i=0;
foreach ($namearray as $a) {
$mynewarray[$i] = $a;
$i++;
}
foreach only works on arrays and puts each key into the $ after the as - what we do with the key is build a new array. Using print_r($mynewarray); we can see that the keys are now the way we want.
Array ( [0] => Ana [1] => Bill [2] => Claudette [3] => Danny [4] => Erika [5] => Fabian [6] => Grace )And using the for loop we used before but referencing $mynewarray
for ($i=0;$i < count($mynewarray);$i++){
echo $mynewarray[$i]."<br>";
}