In this post will learn how to remove the duplicate element from an array using PHP
1- This is our unidimensional array:
$DayofWeek = array('lunes','martes','lunes','miercoles','miercoles','jueves','martes','viernes','miercoles');
Output:
Array
( [0] => lunes [1] => martes [2] => lunes [3] => miercoles [4] => miercoles [5] => jueves [6] => martes [7] => viernes [8] => miercoles )
As you can see we have a duplicate elements to remove the duplicity we can use the php function called array_unique() as follows:
$newArray = array_unique($DayofWeek);
Remember array_unique function will create a new array.This is the output:
Array
(
[0] => lunes
[1] => martes
[3] => miercoles
[5] => jueves
[7] => viernes
)
If you have noticed the array is untidy if you want to sort by the indix , there is a php a php function called sort :
sort($newArray);
This is the output
Array
(
[0] => jueves
[1] => lunes
[2] => martes
[3] => miercoles
[4] => viernes
)
No comments:
Post a Comment