0

How to display once elements of array ?. For example

var array = ["b","c","c","a","d","e","a","d"]

show => ["a","b","c","d","e"] ?

Any example ?

2

5 Answers 5

1

Use the array_unique() function to remove the duplicates and sort - http://php.net/manual/en/function.array-unique.php

Following up with the array_values() function will remove the gaps in the array index - http://php.net/manual/en/function.array-values.php

// initialize array
var $array = array("b","c","c","a","d","e","a","d");
// remove duplicates and sort by string value
$array = array_unique($array, SORT_STRING);
// reindex array (numeric index will have gaps where the duplicates where removed)
$array = array_values($array);
// show results
print_r($array);

In Javascript/jQuery you can use the unique() and sort() methods

// initialize array
var array = ["b","c","c","a","d","e","a","d"];
// remove duplicate values
array.unique();
// sort remaining items
array.sort();

If you are sorting numbers in Javascript, you would need to pass a function, as the array is sorted lexicographically be default

array.sort(function(a,b){return a - b;});
Sign up to request clarification or add additional context in comments.

Comments

1

PHP

array_unique($array, SORT_STRING)

jQuery

array.unique()

Comments

0

in php you should use array_unique and sort for sorting array

$arr = array("b","c","c","a","d","e","a","d");
sort($arr);
print_r(array_unique($arr));

Comments

0
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

source:stack overflow

3 Comments

A much easier solution would be to use names.unique()
yes ,i posted bcoz he asked for solution either in php or js
unique() is a Javascript function, PHP has a similar function array_unique(). Javascript syntax is array.unique() and PHP is array_unique($array).
0

qustion asked:- How to display once elements of array ?. For example

var array = ["b","c","c","a","d","e","a","d"]

show => ["a","b","c","d","e"] ?

Any example ?


answer:- $arr = array("b","c","a","d","e","a","d");

$unique = array_unique($arr);//remove all duplicate values

sort($unique);//sort is done here

echo ""; print_r($unique );//shows show => ["a","b","c","d","e"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.