Arrays are fundamental data structures in PHP that allow developers to store and manipulate multiple values under a single variable. PHP provides a rich set of built-in functions to perform various operations on arrays, making array manipulation efficient and convenient. Two such functions are array_values() and array_unique(). In this article, we will explore these functions and understand how they can be used in combination to manipulate arrays effectively.
PHP array_values() Function
The array_values() function in PHP is a powerful tool that retrieves all the values from an array while discarding their corresponding keys. It creates a new array with sequential integer keys, starting from zero, based on the original array’s values.
The syntax for array_values() is as follows:
array_values(array $array): array
The $array parameter represents the input array from which you want to retrieve the values. The function returns a new array containing only the values.
Example: Using array_values()
Consider the following example:
$fruits = array("apple" => "red", "banana" => "yellow", "orange" => "orange");
$values = array_values($fruits);
print_r($values);
Output:
Array
(
[0] => red
[1] => yellow
[2] => orange
)
In this example, the array_values() function extracts the values from the $fruits array, discards the associative keys, and assigns sequential integer keys to the resulting array. The output displays the values (“red”, “yellow”, “orange”) in the same order as they appeared in the original array.
PHP array_unique() Function
The array_unique() function in PHP is used to remove duplicate values from an array, resulting in a new array with unique values. It preserves the order of the elements while discarding the duplicate occurrences.
The syntax for array_unique() is as follows:
array_unique(array $array, int $sort_flags = SORT_STRING): array
The $array parameter represents the input array from which you want to remove duplicates. The optional $sort_flags parameter allows you to specify the sorting behavior of the resulting array.
Example: Using array_unique()
Consider the following example:
$numbers = array(1, 2, 3, 4, 3, 2, 1);
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
In this example, the array_unique() function removes the duplicate values from the $numbers array, resulting in a new array $uniqueNumbers. The output displays the unique values (1, 2, 3, 4) while maintaining their original order.
Combining array_values() and array_unique()
The array_values() and array_unique() functions can be combined to manipulate arrays effectively. By applying array_values() after array_unique(), we can obtain a new array with unique values and sequential integer keys.
Consider the following example:
$colors = array("red", "green", "blue", "green", "yellow");
$uniqueColors = array_unique($colors);
$uniqueValues = array_values($uniqueColors);
print_r($uniqueValues);
Output:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => yellow
)
In this example, the array_unique() function removes the duplicate values from the $colors array, resulting in $uniqueColors array. Then, array_values() is applied to $uniqueColors to obtain the $uniqueValues array, which has sequential integer keys assigned to the unique values. The output displays the unique values (“red”, “green”, “blue”, “yellow”) with sequential integer keys.
Conclusion
The array_values() and array_unique() functions in PHP are powerful tools for array manipulation. By utilizing array_values(), we can retrieve the values from an array while discarding the keys. On the other hand, array_unique() allows us to remove duplicate values from an array. When combined, these functions enable us to obtain a new array with unique values and sequential integer keys. By understanding and utilizing these functions effectively, PHP developers can manipulate arrays efficiently and perform various array operations with ease.


масла Украина Мы предлагаем полный спектр моторных, трансмиссионных, гидравлических и специализированных масел от ведущих мировых производителей, гарантируя их подлинность и соответствие всем требованиям.
https://thelanote.com/articles/1xbet_promo_code___welcome_bonus_code.html
ко ланта ko lanta
sportaza deutschland sportaza bewertung
купить мужские кроссовки nike В сфере роскоши ключевое значение приобретают неповторимый стиль, высочайшее качество производства и скрупулезное внимание к деталям. Клиенты все чаще отдают предпочтение вещам, которые акцентируют личную уникальность, при этом без труда интегрируясь в повседневные или деловые образы. Следовательно, интерес к дорогим одежде, обуви и аксессуарам остается неизменно высоким.
доставка из китая пойзон в россию Работа с маркетплейсами требует не только понимания продаж, но и внимания к множеству сопутствующих процессов: от оформления карточек и логистики до аналитики, рекламы и финансового учета. Поэтому всё больше предпринимателей ищут практичные решения, которые помогают системно выстраивать работу и лучше контролировать результаты.
сколько стоит тест на отцовство В настоящее время в Самаре пользуются особой популярностью те медицинские учреждения, которые предоставляют возможность консультации у профильного врача, проведения диагностических мероприятий и комплексного решения медицинских вопросов. Для клиентов крайне важно, чтобы процесс получения медицинской помощи был организован максимально комфортно, а консультация, обследование и последующие назначения были ясны и логичны.
шкаф купе 2 двери Приобретая элементы обстановки, стоит уделять внимание не только визуальной привлекательности, но и эргономичности при регулярном использовании. Разумнее заранее проанализировать габариты, структуру, сырье и стилистику, чтобы покупка точно отвечала нуждам определенной локации. Такой подход особенно целесообразен для квартир с нестандартной архитектурой, малогабаритных помещений и интерьеров, где значение имеет любой нюанс.
ответы на отзывы покупателей Бот для ответов на отзывы может работать круглосуточно, обеспечивая своевременную обратную связь.
кайт сафари 2026 обучение кайтсёрфингу в египте
кайт хургада обучение кайтсёрфингу в хургаде
кайт блага кайт школа анапа
ко ланта ко ланта
египет кайт кайт парадайз египет кайт
фасадные мемориальные доски под ключ по РФ Фасадные мемориальные доски и таблички на здания, школы, предприятия, учебные заведения
https://boostwin-casino.clients.site/ буствин промокод
ко ланта ко ланта
Лист нержавеющий Восстановленные трубы представляют собой экономически выгодную альтернативу новым изделиям, сохраняя при этом достаточный уровень надежности для многих применений
Сайт https://nashkvartal.kiev.ua/ присвячений місту Київ: тут зібрані новини, події та поради для жителів. Будьте в курсі всього важливого, що відбувається у столиці.