Уникальное значение функция php

PHP: array_unique() function

The array_unique() is used to remove duplicate values from an array.

Note: The keys are preserved. array_unique() sorts the values treated as a string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

array_unique(array1, sort_flags)
Name Description Required /
Optional
Type
array1 The input array. Required Array
sort_flags sort_flags is used to modify the sorting behavior using following values:
SORT_REGULAR — compare items normally.
SORT_NUMERIC — compare items numerically
SORT_STRING — compare items as strings
SORT_LOCALE_STRING — compare items as strings, based on the current locale
Optional Integer

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 i.e. when the string representation is the same, the first element will be used.

Return value

Value Type: Array

Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )

Pictorial Presentation:

php function reference: array_unique() function

Practice here online :

Previous: array_sum
Next: array_unshift

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

How can I sanitize user input with PHP?

It’s a common misconception that user input can be filtered. PHP even has a (now deprecated) «feature», called magic-quotes, that builds on this idea. It’s nonsense. Forget about filtering (or cleaning, or whatever people call it).

What you should do, to avoid problems, is quite simple: whenever you embed a string within foreign code, you must escape it, according to the rules of that language. For example, if you embed a string in some SQL targeting MySQL, you must escape the string with MySQL’s function for this purpose (mysqli_real_escape_string). (Or, in case of databases, using prepared statements are a better approach, when possible.)

Читайте также:  Ax axis equal python

Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.

A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.

The only case where you need to actively filter data, is if you’re accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

array_unique

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

Обратите внимание, что ключи сохранятся. array_unique() сначала сортирует значения как строки, сохраняет первый встреченный ключ для каждого значения и игнорирует все последующие ключи. Это не означает, что первый ключ каждого значения неотсортированного array будет сохранён.

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

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

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

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

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

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

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

Версия Описание
5.2.10 Значение по умолчанию параметра sort_flags изменено обратно на SORT_STRING .
5.2.9 Добавлен необязательный параметр sort_flags , по умолчанию равный SORT_REGULAR . До версии 5.2.9, это функция сортировала массив с помощью SORT_STRING .

Примеры

Пример #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

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 lang charsequence

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

В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.

Фильтрация данных с помощью zend-filter

Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

Контекстное экранирование с помощью zend-escaper

Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

Подключение Zend модулей к Expressive

Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

Совет: отправка информации в Google Analytics через API

Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

Подборка PHP песочниц

Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

Совет: активация отображения всех ошибок в PHP

При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.

Источник

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