Removing Duplicate Values in PHP

Asked By 10 points N/A Posted on -
qa-featured

I'm a PHP programmer but I'm still a beginner on this particular field.

I want to remove values in the arrays that are duplicates.

How can I do it?

SHARE
Best Answer by Harold kenosi
Best Answer
Best Answer
Answered By 0 points N/A #98940

Removing Duplicate Values in PHP

qa-featured

Dear friend,
Array_unique removes duplicate values from an array.
It takes an input as array and return non duplicate array.
Syntax of array_unique() is as below.

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Here $sort_flags indicate sorting type flag which may be regular, numeric, string & local string.

Examples

<?php

$array =array(1,1,2,3);

$array =array_unique($array);

// Array is now (1, 2, 3) because 1 occurs 2 times.

?>

array_unique() not only removes duplicate numbers, but also it can remove duplicate strings as shown as below.

<?php

$array =array("Ram","Krishna","Ram","Ganesh");

$array =array_unique($array);

//removes “Ram” as it occurs 2 times.

?>

Answered By 0 points N/A #98942

Removing Duplicate Values in PHP

qa-featured

In PHP there is an array function array_unique() which eliminates the duplicates value in an array. If in an array two or more values are same then the first occurrence will be kept and other will be removed.

Function array_unique() takes an array as in input and returns a new array without duplicate values.

<?php

          $colors = array(“a”=>”green”, “b”=>”blue”, “r”=>”red”,”p”=>”blue”);

          $u_array = array_unique($colors);

          Print_r($u_array);

?>

Out Put:

Array (

[a] => green

 [b] => blue

 [r] => red

 )

Login/Register to Answer

Related Questions