- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
PHP array functions
In the previous chapter, we dealt with array initialisation and perusal. In this chapter, we will cover various PHP array functions. These functions enable us to modify, sort, merge, slice, and shuffle the data inside the arrays.
Sorting arrays
First we are going to sort an arrays.
sort.php
<?php $names = [ "Jane", "Rebecca", "Lucy", "Lenka", "Ada" ]; echo "Unsorted: \n"; foreach ($names as $name) { echo "$name "; } echo "\n"; sort($names); echo "Sorted: \n"; foreach ($names as $name) { echo "$name "; } echo "\n"; ?>
In the above script, we have a $names
array. We use the sort()
function to sort the contents of the array.
$ php sort.php Unsorted: Jane Rebecca Lucy Lenka Ada Sorted: Ada Jane Lenka Lucy Rebecca
The output of the script shows unsorted and sorted female names.
The rsort()
function sorts an array in reverse order.
sort2.php
<?php $numbers = [ 12, 3, 5, 1, 6, 7, 10, 0, 9, 8, 11]; sort($numbers); echo "Ascending order: \n"; foreach ($numbers as $n) { echo "$n "; } echo "\n"; rsort($numbers); echo "Descending order: \n"; foreach ($numbers as $n) { echo "$n "; } echo "\n"; ?>
There is an array of integers. It is sorted in ascending and descending order.
sort($numbers);
The sort()
function sorts the integers in ascending order.
rsort($numbers);
The rsort()
function sorts the integers in descending order.
$ php sort2.php Ascending order: 0 1 3 5 6 7 8 9 10 11 12 Descending order: 12 11 10 9 8 7 6 5 3 1 0
This is the output of the sort2.php
script.
In the following example, we show how to sort accented characters.
locale_sort.php
<?php setlocale(LC_ALL, 'sk_SK.utf8'); $words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma", "zem", "autor", "ceduľa", "čižma"]; sort($words, SORT_LOCALE_STRING); echo "Ascending order: \n"; foreach ($words as $w) { echo "$w "; } echo "\n"; rsort($words, SORT_LOCALE_STRING); echo "Descending order: \n"; foreach ($words as $w) { echo "$w "; } echo "\n"; ?>
We have an array of Slovak words which contain specific accents.
setlocale(LC_ALL, 'sk_SK.utf8');
We set the Slovak locale using the setlocale()
function. A locale represents a specific geographical, political, or cultural region.
$words = [ "ďateľ", "auto", "železo", "byt", "kocka", "dáma", "zem", "autor", "ceduľa", "čižma"];
The $words
is an array of accented Slovak words.
sort($words, SORT_LOCALE_STRING);
We sort the array in ascending order with the sort()
function. We pass the SORT_LOCALE_STRING
flag to the function, which tells sort()
to take the locale into account.
$ php locale_sort.php Ascending order: auto autor byt ceduľa čižma dáma ďateľ kocka zem železo Descending order: železo zem kocka ďateľ dáma čižma ceduľa byt autor auto
The words are correctly sorted according to the Slovak standards.
Sometimes we need to perform custom sorting. For custom sorting, we have the usort()
function in PHP.
custom_sorting.php
<?php $names = [ "Michael Brown", "Albert Einstein", "Gerry Miller", "Tom Willis", "Michael Gray", "Luke Smith" ]; function sort_second_names($a, $b) { $name1 = explode(" ", $a); $name2 = explode(" ", $b); return strcmp($name1[1], $name2[1]); } usort($names, 'sort_second_names'); foreach ($names as $name) { echo "$name\n"; } echo "\n"; ?>
We have an array of full names. The sort()
function would sort these strings according to the first names, because they precede the second names. We create a solution to sort these names according to their second names.
function sort_second_names($a, $b) { $name1 = explode(" ", $a); $name2 = explode(" ", $b); return strcmp($name1[1], $name2[1]); }
We have a custom sorting function. The names are split by the explode()
function and the second names are compared with the strcmp()
function.
usort($names, 'sort_second_names');
The usort()
function accepts the comparing function as its second parameter.
$ php custom_sorting.php Michael Brown Albert Einstein Michael Gray Gerry Miller Luke Smith Tom Willis
The names are correctly sorted according to their second names.
Counting values in arrays
The count()
function counts the number of elements in the array. The array_sum()
function calculates the sum of all values. The array_product()
function calculates the product of values in the array.
counting.php
<?php $numbers = [ 1, 2, 4, 5, 2, 3, 5, 2 ]; $len = count($numbers); $sum = array_sum($numbers); $prod = array_product($numbers); echo "In the array, there are $len numbers\n"; echo "The sum of the numbers is $sum\n"; echo "The product of the numbers is $prod\n"; ?>
In the example, we have an array of numbers. We apply the above defined functions on the array.
$ php counting.php In the array, there are 8 numbers The sum of the numbers is 24 The product of the numbers is 2400
This is the output of the script.
Unique values
In the following example, we find out unique values in an array.
unique.php
<?php $numbers = array(3, 4, 4, 3, 2, 4); $count_values = array_count_values($numbers); print_r($count_values); $unique = array_unique($numbers); print_r($unique); ?>
In this script, we have duplicates in the array. The array_count_values()
function returns an array with the number of occurrences for each value. The array_unique()
function returns an array without duplicates.
$ php unique.php Array ( [3] => 2 [4] => 3 [2] => 1 ) Array ( [0] => 3 [1] => 4 [4] => 2 )
The first array says that 3 is present twice, 4 three times, and 2 once. The second array says that there are three values present in the array: 3, 4, and 2. Value 3 has index 0, 4 has index 1 and 2 has index 4. The array_unique()
function keeps the indexes untouched.
Slicing arrays
The array_slice()
function returns a sequence of elements from an array as specified by its offset and length parameters.
slicing.php
<?php $nums = range(1, 20); $slice1 = array_slice($nums, 0, 3); echo "Slice1:\n"; foreach ($slice1 as $s) { echo "$s "; } echo "\n"; $slice2 = array_slice($nums, -3); echo "Slice2:\n"; foreach ($slice2 as $s) { echo "$s "; } echo "\n"; ?>
In the example, we create two slices of an array of integers.
$slice1 = array_slice($nums, 0, 3);
We create a slice starting from the first element; the length of the slice is three elements.
$slice2 = array_slice($nums, -3);
By giving a negative offset, the slice is created from the end of the array.
$ php slicing.php Slice1: 1 2 3 Slice2: 18 19 20
This is the output of the slicing.php
example.
Array pointer
PHP has an internal array pointer. In the following example, we present functions that manipulate this pointer.
array_pointer.php
<?php $continents = [ "America", "Africa", "Europe", "Asia", "Australia", "Antarctica" ]; $item1 = current($continents); $item2 = next($continents); $item3 = next($continents); $item4 = end($continents); $item5 = prev($continents); echo "$item1, $item2, $item3, $item4, $item5\n"; reset($continents); while(list($idx, $val) = each($continents)) { echo "Index: $idx, Value: $val\n"; } ?>
In this example, we traverse the array using the functions that move the internal array pointer.
$item1 = current($continents); $item2 = next($continents); $item3 = next($continents); $item4 = end($continents); $item5 = prev($continents);
The current()
function returns the current element in the array. At the beginning, it is the first element of the array. The next()
function advances the pointer by one position. The end()
function returns the last element. The prev()
element returns the element, one position before the current one. In our case it is the next to the last element.
reset($continents); while(list($idx, $val) = each($continents)) { echo "Index: $idx, Value: $val\n"; }
Here we use the reset()
function to set the internal pointer to the first element again and peruse the $continents
array one more time.
$ php array_pointer.php America, Africa, Europe, Antarctica, Australia Index: 0, Value: America Index: 1, Value: Africa Index: 2, Value: Europe Index: 3, Value: Asia Index: 4, Value: Australia Index: 5, Value: Antarctica
This is the output of the array_pointer.php
script.
Merging arrays
The array_merge()
function merges arrays.
merge.php
<?php $names1 = [ "Jane", "Lucy", "Rebecca" ]; $names2 = [ "Lenka", "Timea", "Victoria" ]; $names = array_merge($names1, $names2); foreach ($names as $name) { echo "$name "; } echo "\n"; ?>
In this example, we have two arrays: $names1
and $names2
. We use the array_merge()
function to create $names
array by merging the previous two arrays.
$ php merge.php Jane Lucy Rebecca Lenka Timea Victoria
The new array has six names.
Modifying arrays
It is possible to modify PHP arrays with array_push()
, array_pop()
, array_shift()
, or array_unshift()
functions.
modify.php
<?php $numbers = [ 1, 2, 3, 4 ]; array_push($numbers, 5, 6); foreach ($numbers as $num) { echo $num, " "; } echo "\n"; array_pop($numbers); foreach ($numbers as $num) { echo $num, " "; } echo "\n"; array_unshift($numbers, -1, 0); foreach ($numbers as $num) { echo $num, " "; } echo "\n"; array_shift($numbers); foreach ($numbers as $num) { echo $num, " "; } echo "\n"; ?>
In the above script, we use functions that modify the contents of an array. We have a $numbers
array that has 4 numbers: 1, 2, 3, and 4.
array_push($numbers, 5, 6);
The array_push()
function inserts one or more items to the end of the array. Our array now contains values 1, 2, 3, 4, 5, and 6.
array_pop($numbers);
The array_pop()
function removes the last item from the array. Our array stores now numbers 1, 2, 3, 4, and 5.
array_unshift($numbers, -1, 0);
The array_unshift()
function adds -1 and 0 to the beginning of the array. The array contains values -1, 0, 1, 2, 3, 4, and 5.
array_shift($numbers);
Finally, the array_shift()
function removes the first item from the array. Now we have values 0, 1, 2, 3, 4, and 5 in the array.
$ php modify.php 1 2 3 4 5 6 1 2 3 4 5 -1 0 1 2 3 4 5 0 1 2 3 4 5
This is the output of the modify.php
example.
The range() function
The range()
function simplifies array creation by automatically creating a sequence of elements. It accepts three parameters: start of sequence, end of sequence, and an optional increment, which defaults to 1.
range.php
<?php $numbers1 = range(1, 15); foreach ($numbers1 as $num) { echo "$num "; } echo "\n"; $numbers2 = range(15, 1, -1); foreach ($numbers2 as $num) { echo "$num "; } echo "\n"; ?>
The range()
function enables us to create a list of consecutive numbers easily.
$numbers1 = range(1, 15);
An array with numbers 1, 2, ... 15 is created.
$numbers2 = range(15, 1, -1);
It is possible to create a descending sequence of values by specifying a negative increment.
$ php range.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
This is the output of the range.php
function.
Randomizing array values
The array_rand()
function picks one or more random entries from an array. The shuffle()
function randomizes the order of the elements in an array.
randomize.php
<?php $nums = range(1, 20); echo ($nums[array_rand($nums)]) . "\n"; $r = array_rand($nums, 2); echo $nums[$r[0]] . "\n"; echo $nums[$r[1]] . "\n"; shuffle($nums); foreach ($nums as $n) { echo "$n "; } echo "\n"; ?>
In the example, we pick random values from the array and randomize its order of elements.
echo ($nums[array_rand($nums)]) . "\n";
The array_rand()
function returns a random key from the $num
array.
$r = array_rand($nums, 2);
In this case, the array_rand()
function returns an array of two random keys.
$ php randomize.php 4 2 19 13 19 4 3 17 11 20 16 10 9 8 14 15 12 18 2 6 5 1 7
This is a sample output of the randomize.php
program.
The in_array() function
The in_array()
function checks if a specific element is inside an array.
inarray.php
<?php $names = [ "Jane", "Adriana", "Lucy", "Rebecca" ]; if (in_array("Jane", $names)) { echo "Jane is in the array\n"; } else { echo "Jane is not in the array\n"; } if (in_array("Monica", $names)) { echo "Monica is in the array\n"; } else { echo "Monica is not in the array\n"; } ?>
Our script checks if 'Jane' and 'Monica' is in the $names
array.
$ php inarray.php Jane is in the array Monica is not in the array
'Jane is in the array, but 'Monica' is not.
Keys and values
PHP array is an associative array which consists of key and value pairs.
keysvalues.php
<?php $domains = [ "sk" => "Slovakia", "de" => "Germany", "hu" => "Hungary", "ru" => "Russia" ]; $keys = array_keys($domains); $values = array_values($domains); foreach ($keys as $key) { echo "$key "; } echo "\n"; foreach ($values as $value) { echo "$value "; } echo "\n"; ?>
The array_keys()
function returns all the keys of an array. The array_values()
function returns all the values of an array.
$ php keysvalues.php sk de hu ru Slovakia Germany Hungary Russia
The first line consists of top level domain names. These were the keys of the $domains
array. The second line are the names of the corresponding countries. These were the values of the array.
The array_walk() function
The array_walk()
function applies a user defined function to every member of the array.
array_walk.php
<?php $countries = [ "de" => "Germany", "sk" => "Slovakia", "us" => "United States", "ru" => "Russia", "hu" => "Hungaria", "pl" => "Poland" ]; function show_values($value, $key) { echo "The $key stands for the $value\n"; } array_walk($countries, 'show_values'); ?>
We have a $countries
array. We apply the show_values
function to each element of the array. The function simply prints the key and the value for each element.
$ php array_walk.php The de stands for the Germany The sk stands for the Slovakia The us stands for the United States The ru stands for the Russia The hu stands for the Hungaria The pl stands for the Poland
This is the output of the array_walk()
function.
In this part of the PHP tutorial, we covered some PHP array functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论