Php array только уникальные значения

array_unique

Принимает входной массив array и возвращает новый массив без повторяющихся значений.

Обратите внимание, что ключи сохранятся. Если в соответствии с заданными flags несколько элементов определяются как идентичные, то будут сохранены ключ и значение первого такого элемента.

Замечание: Два элемента считаются одинаковыми в том и только в том случае, если (string) $elem1 === (string) $elem2 . Другими словами: если у них одинаковое строковое представление, то будет использован первый элемент.

Список параметров

Можно использовать необязательный второй параметр flags для изменения поведения сортировки с помощью следующих значений:

  • SORT_REGULAR — нормальное сравнение элементов (типы не меняются)
  • SORT_NUMERIC — элементы сравниваются как числа
  • SORT_STRING — элементы сравниваются как строки
  • SORT_LOCALE_STRING — сравнивает элементы как строки, с учетом текущей локали.

Возвращаемые значения

Возвращает отфильтрованный массив.

Список изменений

Версия Описание
7.2.0 Если flags равен SORT_STRING , ранее массив array копировался, а не уникальные элементы удалялись (сохраняя значения цифровых индексов), но теперь создается новый массив путем добавления уникальных элементов. Это может привести к различным числовым индексам.

Примеры

Пример #1 Пример использования array_unique()

$input = array( «a» => «green» , «red» , «b» => «green» , «blue» , «red» );
$result = array_unique ( $input );
print_r ( $result );
?>

Результат выполнения данного примера:

Array ( [a] => green [0] => red [1] => blue )

Пример #2 array_unique() и типы:

$input = array( 4 , «4» , «3» , 4 , 3 , «3» );
$result = array_unique ( $input );
var_dump ( $result );
?>

Результат выполнения данного примера:

Источник

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
Читайте также:  Java media framework api

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:

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.

Источник

Remove Duplicate values from an Array in PHP

The array_unique() method is used to remove repeated or duplicate values from the array and return an array.

It is better to use this method on the array if there is some possibility of the same values or the later code in the program depends on it for example – selecting records based on ids and displaying them on the screen.

In this tutorial, I show how you can remove duplicate values from –

  • An Indexed,
  • Associative array and
  • Remove index by key name in the associative array.

Remove Duplicate values from an Array in PHP

Contents

1. Remove duplicate value from Indexed Array

Define an array $num_arr where I also added some duplicate numbers.

Pass the array in array_unique() method to remove duplicate values.

"; print_r($num_arr); echo "

«; echo «After remove duplicate«; echo «

"; print_r($num_unique); echo "

«;

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 1 [4] => 6 [5] => 1 [6] => 23 [7] => 2 ) After remove duplicate Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 6 [6] => 23 )

2. Remove duplicate value from Associative Array

Define an associative array $student_arr with name and age keys.

By calling array_unique() method it will remove those indexes which have name and age key values that are common.

NOTE – I passed SORT_REGULAR as second parameter in array_unique() method.

 "Yogesh Singh","age"=>24); $student_arr[] = array("name" => "Sonarika Bhadoria","age"=>24); $student_arr[] = array("name" => "Anil Singh","age" => 23); $student_arr[] = array("name" => "Yogesh Singh","age" => 24); $student_arr1 = array_unique($student_arr,SORT_REGULAR); echo "
"; print_r($student_arr); echo "

"; echo "After remove duplicate"; echo "

"; print_r($student_arr1); echo "

";

Array ( [0] => Array ( [name] => Yogesh Singh [age] => 24 ) [1] => Array ( [name] => Sonarika Bhadoria [age] => 24 ) [2] => Array ( [name] => Anil Singh [age] => 23 ) [3] => Array ( [name] => Yogesh Singh [age] => 24 ) ) After remove duplicate Array ( [0] => Array ( [name] => Yogesh Singh [age] => 24 ) [1] => Array ( [name] => Sonarika Bhadoria [age] => 24 ) [2] => Array ( [name] => Anil Singh [age] => 23 ) )

3. Remove by key from Associative Array

Define an associative array $student_arr .

Create unique_key() function which takes an array and key name by which remove duplicate indexes.

In this function loop on the $array and check if $keyname isset on the $new_array or not. If not set then assign $value in $new_array[$value[$keyname]] .

Reindex the $new_array with array_values() and return it.

$value) < if(!isset($new_array[$value[$keyname]]))< $new_array[$value[$keyname]] = $value; >> $new_array = array_values($new_array); return $new_array; > // Array $student_arr[] = array("name" => "Yogesh Singh","age"=>24); $student_arr[] = array("name" => "Sonarika Bhadoria","age"=>24); $student_arr[] = array("name" => "Anil Singh","age" => 23); $student_arr[] = array("name" => "Mayank Patidar","age" => 25); $student_arr[] = array("name" => "Anil Singh","age" => 19); // Remove duplicate value according to 'name' $student_unique_arr = unique_key($student_arr,'name'); echo "
"; print_r($student_arr); echo "

"; echo "Array after remove duplicate key"; echo "

"; print_r($student_unique_arr); echo "

";

Array ( [0] => Array ( [name] => Yogesh Singh [age] => 24 ) [1] => Array ( [name] => Sonarika Bhadoria [age] => 24 ) [2] => Array ( [name] => Anil Singh [age] => 23 ) [3] => Array ( [name] => Mayank Patidar [age] => 25 ) [4] => Array ( [name] => Anil Singh [age] => 19 ) ) Array after remove duplicate key Array ( [0] => Array ( [name] => Yogesh Singh [age] => 24 ) [1] => Array ( [name] => Sonarika Bhadoria [age] => 24 ) [2] => Array ( [name] => Anil Singh [age] => 23 ) [3] => Array ( [name] => Mayank Patidar [age] => 25 ) )

4. Conclusion

Pass your array in the array_unique() method to remove common values it works with both indexed and associative array.

If you like to remove array indexes according to key name in associative then you can use above-created unique_key() function and customize it according to your preference.

If you found this tutorial helpful then don’t forget to share.

Источник

array_unique

Принимает входной array и возвращает новый массив без повторяющихся значений.

Обратите внимание, что ключи сохранены. Если несколько элементов сравниваются как равные под заданными flags , то ключ и значение первого равного элемента будут сохранены.

Примечание : два элемента считаются равными тогда и только тогда, когда (string) $elem1 === (string) $elem2 т.е. когда строковое представление одинаково, будет использоваться первый элемент.

Parameters

Необязательные flags второго параметра могут использоваться для изменения поведения сортировки с использованием этих значений:

Флаги сортировочного типа:

  • SORT_REGULAR — сравнивать элементы в обычном режиме (не менять типы)
  • SORT_NUMERIC — сравнить элементы численно
  • SORT_STRING — сравнивать элементы как строки
  • SORT_LOCALE_STRING — сравнивать элементы как строки на основе текущего языкового стандарта.

Return Values

Возвращает отфильтрованный массив.

Changelog

Version Description
7.2.0 Если flags — SORT_STRING , ранее array был скопирован, а неуникальные элементы были удалены (без последующей упаковки массива), но теперь новый массив создается путем добавления уникальных элементов. Это может привести к разным числовым индексам.

Examples

Пример # 1 array_unique () Пример

 $input = array("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique($input); print_r($result); ?>

Выводится приведенный выше пример:

Array ( [a] => green [0] => red [1] => blue )

Пример # 2 array_unique () и типы

 $input = array(4, "4", "3", 4, 3, "3"); $result = array_unique($input); var_dump($result); ?>

Выводится приведенный выше пример:

array(2) < [0] => int(4) [2] => string(1) "3" >

Notes

Примечание : обратите внимание, что array_unique () не предназначен для работы с многомерными массивами.

See Also

PHP 8.2

(PHP 5,7,8)array_uintersect_assoc Вычисляет пересечение массивов с дополнительной проверкой индекса,сравнивает данные функцией обратного вызова Обратите внимание,что

(PHP 5,7,8)array_uintersect_uassoc Вычисляет пересечение массивов с дополнительной проверкой индексов,сравнивает данные и индексы с помощью отдельных функций обратного вызова

(PHP 4,5,7,8)array_unshift Добавление одного или нескольких элементов в начало массива array_unshift()добавляет переданные элементы в начало Примечание:Сброс.

(PHP 4,5,7,8)array_values Возвращает все значения массива array_values()возвращает все значения from и индексы в числовом виде.

Источник

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