Php unique array index

PHP array_unique() Function

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

Note: The returned array will keep the first array item’s key type.

Syntax

Parameter Values

  • SORT_STRING — Default. Compare items as strings
  • SORT_REGULAR — Compare items normally (don’t change types)
  • SORT_NUMERIC — Compare items numerically
  • SORT_LOCALE_STRING — Compare items as strings, based on current locale

Technical Details

Return Value: Returns the filtered array
PHP Version: 4.0.1+
PHP Changelog: PHP 7.2: If sorttype is SORT_STRING, this returns a new array and adds the unique elements.
PHP 5.2.9: The default value of sorttype was changed to SORT_REGULAR.
PHP 5.2.1: The default value of sorttype was changed back to SORT_STRING.

❮ PHP Array Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Читайте также:  Java list string and string

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP Array Unique: Learn To Remove Duplicate Values From Arrays

Position Is Everything

What is php array unique

The PHP array unique is a function that allows removing duplicate values from an array while returning an array of unique values only. This implies that the given function isn’t anything less than a system that allows only one entry for a particular id. Therefore, we created this article to help you filter out the repetitive values from an array.

Keep reading to create an identity check system that doesn’t allow multiple array entries based on repetitive values.

What is PHP array_unique?

The PHP array_unique function accepts an array, removes all its duplicate values, and returns the array. It would be beneficial to keep in mind that the keys of the unique values will be preserved. So, the given function is as easy to use as a customized filter paper that allows only the first-found unique values to pass through it.

Now, please have a look at its syntax: array_unique(array, flag) . Here, the flag parameter is optional and its default value is set to “SORT_STRING,” which means that the array values will be compared as strings.

Also, you can use the following flags for customizing the comparison:

  • SORT_REGULAR: It doesn’t change the data types of the array values
  • SORT_NUMERICC: It changes the array values to integers before comparing them
  • SORT_LOCALE_STRING: It compares the array values as strings according to the current locale

– Coding Example

For example, let’s assume that your program contains an array that might contain duplicate values. So, here you’ll use the array unique function to remove duplicates from array PHP like the code snippet given below:

// creating an array of animals
$animals = array(“Cat”,”Dog”,”Tiger”,”Lion”,”Cat”);
// using the PHP array_unique function and printing the unique array
print_r(array_unique($animals));
?>

The following output will be displayed on your browser:

Array ( [0] => Cat [1] => Dog [2] => Tiger [3] => Lion )

Array_unique in PHP: Working With Associative Arrays

Does the functioning of the PHP array unique function change when you use it with an associative array? Well, the stated function works the same way as discussed above and matches the array values before generating an array of unique values.

– Coding Example for PHP array_unique With Associative Array

For example, you have an associative array of fruits but there is a chance that the array might contain the same fruit names more than once. So, in this situation, you’ll use the PHP array unique function to get an array of unique fruit names.

Please refer to the following example code snippet of the PHP array unique function:

?php
// creating an array of fruits
$fruits = array(
“One” => “Mango”,
“Two” => “Apple”,
“Three” => “Strawberry”,
“Four” => “Pineapple”,
“Two” => “Apple”, // duplicate value
“Five” => “Mango”, // duplicate value
);
// using the PHP array_unique function and printing the unique array
print_r(array_unique($fruits));
?>

This is the output that you’ll get:

Array ( [One] => Mango [Two] => Apple [Three] => Strawberry [Four] => Pineapple )

PHP Array Unique Values: Multidimensional Array

Can the PHP array unique function help in dealing with duplication in multidimensional arrays? Actually, the PHP array unique function doesn’t work with the multidimensional arrays but still, there is an alternative to it. Creating a user-defined function can help you in removing duplicate arrays from the main array based on a particular key. However, remember that the keys of the original array won’t be preserved.

– Coding Example

For example, there might be a case in which you have a multidimensional array containing the details of the employees. Now, you want to remove the whole inner array if its id key has a duplicate value. So, you’ll create a custom function that accepts an array and a key. The custom function uses the foreach loop and the in_array() function to check the uniqueness of the particular key.

Now, take a look at this code snippet that’ll make the understanding of this example easier for you:

// creating an array of employee details
$emp = array(
array(“id” => 1,”Position” => “Manager”,”Date” => “01-June-2020”),
array(“id” => 2,”Position” => “IT Incharge”, “Date” => “02-July-2020”),
array(“id” => 3,”Position” => “Accountant”,”Date” => “02-July-2020”),
array(“id” => 1,”Position” => “HR”, “Date” => “03-June-2020”),
);
// creating a custom function
function multi_unique_array($arr, $key) <
$Myarray = array();
$i = 0;
$array_of_keys = array();
foreach($arr as $val) <
if (!in_array($val[$key], $array_of_keys)) <
$array_of_keys[$i] = $val[$key];
$Myarray[$i] = $val;
>
$i++;
>
return $Myarray;
>
// calling the custom function with array and id key
$unique = multi_unique_array($emp,”id”);
// printing the multidimensional array with unique ids
print_r($unique);
?>

You’ll get the result below after running the code above:

Array (
[0] => Array ( [id] => 1 [Position] => Manager [Date] => 01-June-2020 )
[1] => Array ( [id] => 2 [Position] => IT Incharge [Date] => 02-July-2020 )
[2] => Array ( [id] => 3 [Position] => Accountant [Date] => 02-July-2020 )
)

– Note:

It isn’t important to have a multidimensional array with named keys to use the above function. You can simply pass “0” as the second argument to remove all the inner arrays that contain even a single duplicate value.

PHP Array Remove Duplicates: Only Repetitive Arrays

Certainly, the inner arrays of a multidimensional array may not contain all the duplicate values. Moreover, there can be a situation when you don’t want to remove the inner arrays based on a single duplicate value as discussed in the above example.

In that case, would you like to check all the values of the inner arrays before removing them?

Then don’t worry; you can achieve it as well by making a few changes in the custom function created above.

– Coding Example

For example, let’s say you have a multidimensional array of students in which each inner array consists of two values representing the student id and subject. Here, a student can study multiple subjects. Moreover, the same subject can be chosen by different students. So, you want to remove only those inner arrays that are completely duplicated.

Please have a look at the example code snippet given below:

$student = array(
array(“std1″,”English”),
array(“std1″,”Physics”),
array(“std2″,”English”),
array(“std2″,”Chemistry”),
array(“std2″,”Physics”),
array(“std3″,”English”),
array(“std2″,”English”), // duplicate
array(“std3″,”Sociology”),
array(“std3″,”Sociology”), // duplicate
array(“std4″,”English”),
array(“std1″,”Physics”), // duplicate
array(“std4″,”Chemistry”)
);
// creating a custom function
function multi_unique($array) <
$Myarray = array();
$array3 = array();
foreach($array as $val) <
if (!in_array($val, $array3)) <
$array3[] = $val;
$Myarray[] = $val;
>
>
return $Myarray;
>
$res = multi_unique($student);
print_r($res);
?>

This will be the output displayed on the browser:

Array (
[0] => Array ( [0] => std1 [1] => English )
[1] => Array ( [0] => std1 [1] => Physics )
[2] => Array ( [0] => std2 [1] => English )
[3] => Array ( [0] => std2 [1] => Chemistry )
[4] => Array ( [0] => std2 [1] => Physics )
[5] => Array ( [0] => std3 [1] => English )
[6] => Array ( [0] => std3 [1] => Sociology )
[7] => Array ( [0] => std4 [1] => English )
[8] => Array ( [0] => std4 [1] => Chemistry )
)

– Note:

The custom function used in the above code snippet won’t preserve the keys of the original array. If you want to preserve the keys then try out the following method.

Get Unique Values From Array: Using Array Functions

Although the user-defined functions help in getting unique values from the multidimensional arrays, the perseverance of keys can be an important task as well. Hence, a combination of array functions such as array_intersect_key, PHP array_unique, and array_map can help in solving the issue. However, you won’t be able to remove the inner arrays based on a particular key by using the stated combination.

– Coding Example for Using PHP Array Unique With Other Functions

Working on the same scenario from the previous example, here is a code snippet that will help you in preserving keys:

$get_unique = array_intersect_key($student , array_unique(array_map(‘serialize’ , $student)));
print_r($get_unique);
?>
Array (
[0] => Array ( [0] => std1 [1] => English )
[1] => Array ( [0] => std1 [1] => Physics )
[2] => Array ( [0] => std2 [1] => English )
[3] => Array ( [0] => std2 [1] => Chemistry )
[4] => Array ( [0] => std2 [1] => Physics )
[5] => Array ( [0] => std3 [1] => English )
[7] => Array ( [0] => std3 [1] => Sociology )
[9] => Array ( [0] => std4 [1] => English )
[11] => Array ( [0] => std4 [1] => Chemistry )
)

Conclusion

The PHP array unique function helps in getting unique values from both indexed and associative arrays. Moreover, it works with other array functions to deal with the duplication in multidimensional arrays. Although you have already learned enough about making arrays unique, here are a few important points to enhance your clarity regarding the topic:

  • The PHP array unique function accepts an array and removes all the duplicate values from it while preserving the keys
  • The PHP array unique returns an array with unique values
  • You can use the optional flag parameter to change the type of the values before comparing them
  • The default value for the flag parameter is set to SORT_STRING
  • The PHP array unique function doesn’t work with multidimensional arrays
  • You can create a user-defined function to remove duplication from multidimensional arrays based on a particular key
  • A user-defined function can help in getting unique values from multidimensional arrays without considering the keys
  • You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys

Php array unique

Through our guide, now, you can instantly remove the duplicate values from arrays without any difficulty.

Источник

Оцените статью