Chapter 5 PHP Array Operation_PHP Tutorial
one. What is an array
An array is a set of elements that share certain characteristics, including similarity and type.
Each element is distinguished by a special identifier, called a key, and each key has a value
1. Two ways to create an array:
1.1 Use the array() function
$usernames = array ('Alerk', 'Mary' , 'Lucy', 'Bob', 'Jack', 'John', 'Mark' );
foreach ( $usernames as $name )
{
echo $name . '
}
?>
output
Alerk
Mary
Lucy
Bob
Jack
John
Mark
1.2 Use range() function
$ numbers = range ( 0, 10 );
foreach ( $numbers as $num )
{
echo $num . '
';
}
$letters = range ( 'a', 'z' );
foreach ( $letters as $letter )
{
echo $letter . '
';
}
? >
output
0
1
2
3
4
5
6
7
8
9
10
a
c
d
e
f
g
h
i
j
k
l
m
o
q
r
t
u
v
w
x
y
z
2. Two ways to loop through array elements:
2.1 for loop
//The third parameter of range represents the step size
$numbers = range(1,10,2);
for($i = 0 ;$i
echo $numbers[$i].'
';
}
?>
output
1
3
5
7
9
2.2 foreach loop
$letters = range('a','h',2);
foreach($letters as $letter )
{
echo $letter.'
';
}
?>
output
a
c
e
g
Foreach can also be used to output the subscript and corresponding value of the array
$letters = range('a','g',2);
foreach($letters as $key => $value)
{
echo $key.'---'.$value.'
';
}
?>
output
0-- -a
1---c
2---e
3---g
3.is_array() function, used to determine whether the variable is an array
$numbers = range(1,10,2);
if( is_array($numbers))
{
foreach($numbers as $num)
{
echo $num.'
';
}
}
else
{
echo $numbers;
}
?>
4.print_r function, prints easy-to-understand information about variables
$usernames = array ('Jackie', 'Mary', 'Lucy ', 'Bob', 'Mark', 'John' );
print_r ( $usernames );
?>
output
Array ( [0] => ; Jackie [1] => Mary [2] => Lucy [3] => Bob [4] => Mark [5] => John )
The source code can be seen as:
Array
(
[0] => Jackie
[1] => Mary
[2] => Lucy
[3] => Bob
[4] => Mark
[5] => John
)
2. Custom key array
1. If you don’t want to create an array with the default subscript zero, you can use the following method to create an array with keys as strings
//Initialize array
$userages = array('Jack'=> 23,'Lucy'=>25,' Mark'=>28);
//Accessing each element of the array
echo $userages['Jack'].'
';
echo $userages['Lucy']. '
';
echo $userages['Mark'].'
';
?>
2. Go to Customize Append elements to the key array
//Initialize array
$ages = array('Jack'=>23);
//Append elements
$ages['Lucy' ]=25;
$ages['Mark']=28;
foreach($ages as $key => $value)
{
echo $key.'----' .$value.'
';
}
?>
3. Add elements directly without creating an array.
//Add directly without creating an array
$ ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
foreach($ages as $key => $value )
{
echo $key.'----'.$value.'
';
}
?>
4. Use of loop printing array foreach
$ages[ 'Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
foreach($ages as $key => $value)
{
echo $key.'=>'.$value.'
';
}
?>
5. each () -- Returns the current key/value pair in the array and moves the array pointer forward one step
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
$ a = each($ages);
print_r($a);
echo '
';
$a = each($ages);
print_r($a) ;
echo '
';
$a = each($ages);
print_r($a);
?>
Use each() function to do loop printing
$ages[ 'Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
while(!! $element = each($ages))
{
print_r($element);
echo '
';
}
?>
Another printing method
$ages['Jack']=23;
$ ages['Lucy']=25;
$ages['Mark']=28;
while(!! $element = each($ages))
{
echo $element[' key'].'=>'.$element['value'];
echo '
';
}
?>
6. Use of the list() function - assign the values in the array to some variables
< ;?php
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
list($name, $age)= each($ages);
echo $name.'=>'.$age;
?>
Use list loop to print the results
$ages['Jack']=23;
$ages ['Lucy']=25;
$ages['Mark']=28;
while(!!list($name,$age)= each($ages))
{
echo $name.'=>'.$age.'
';
}
?>
output
Jack=>23
Lucy=>25
Mark=>28
7. Use of reset() function--point the internal pointer of the array to the first unit
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
each($ages);
each($ages);
list($name,$age)= each($ages);
echo $name.'=>'.$age.'
';
//Reset the array to the beginning of the array
reset($ages);
list($ name,$age)= each($ages);
echo $name.'=>'.$age.'
';
?>
Output
Mark=>28
Jack=>23
8. array_unique() -- Remove duplicate values in the array
$nums = array(1,2,3,4,5,6,5,4,3,2,1, 1,2,3,4,5,6);
//Return an array that does not contain duplicate values
$result = array_unique($nums);
print_r($result);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
9. array_flip ()-- Swap the keys and values in the array
$userages = array('Jack'=> 23,'Lucy'=> ;25,'Mark'=>28);
$ages = array_flip($userages);
print_r($ages);
?>
output
Array ( [23] => Jack [25] => Lucy [28] => Mark )
3. The array
in the array is not necessarily a list of keywords and values. You can also put the array
$produces = array(
array('apple',6,28.8),
array('pear',3,15.6),
array('banana',10,4.6)
);
echo $produces[0][0].'|'.$produces[0][1].'|'.$produces[ 0][2].'
';
echo $produces[1][0].'|'.$produces[1][1].'|'.$produces[1][2 ].'
';
echo $produces[2][0].'|'.$produces[2][1].'|'.$produces[2][2].'< ;br>';
?>
output
apple|6|28.8
pear|3|15.6
banana|10|4.6
Use for Loop to print the array within the array
$produces = array (
array ('apple', 6, 28.8 ),
array ('pear', 3, 15.6 ),
array ('banana', 10, 4.6 )
);
for ($i = 0; $i < count ( $produces ); $i ++)
{
for($j = 0; $j < count ( $produces [$i] ); $ j ++)
{
echo '|' . $produces[$i][$j];
}
echo '
';
}
? >
output
|apple|6|28.8
|pear|3|15.6
|banana|10|4.6
Two-dimensional array
$produces = array (
array ('name' => 'apple', 'amount' => 6, 'price' => 28.8 ),
array ('name' => 'pear', 'amount' => 3, 'price' => 15.6 ),
array ('name' => 'banana', 'amount' => 10, 'price' => 4.6 )
);
while(!!List($key ,$value)=each($produces))
{
while(!!list($key2,$value2)=each($value))
{
echo '|'.$ key2.'=>'.$value2;
}
echo '
';
}
?>
output
| name=>apple|amount=>6|price=>28.8
|name=>pear|amount=>3|price=>15.6
|name=>banana|amount= >10|price=>4.6
It is easier to print with foreach (recommended)
$produces = array (
array ('name' => 'apple', 'amount' => 6, 'price' => 28.8 ),
array ('name' => 'pear', 'amount' => 3, 'price' => 15.6 ),
array ('name' => 'banana', 'amount' => ; 10, 'price' => 4.6 )
);
foreach($produces as $key1 => $value1)
{
foreach($value1 as $key2 => $ value2)
{
echo '|'.$key2.'=>'.$value2;
}
echo '
';
}
?> ;
output
|name=>apple|amount=>6|price=>28.8
|name=>pear|amount=>3|price= >15.6
|name=>banana|amount=>10|price=>4.6
IV. Sorting of arrays
1. Sort of English by the Sort() function
< meta http-equiv="content-type" content="text/html;charset=utf-8" />
$fruits = array('lemo','banana',' apple','pear');
echo 'Original array:';
print_r($fruits);
echo '
';
sort($fruits);
echo 'Sorted array:';
print_r($fruits);
?>
output
Original array: Array ( [0] = > lemo [1] => banana [2] => apple [3] => pear )
Sorted array: Array ( [0] => apple [1] => banana [ 2] => lemo [3] => pear )
2.Sort() function to sort Chinese
$fruits = array('lemon','banana','apple','pear');
echo 'Original array:';
print_r($fruits);
echo '
';
sort($fruits);
echo 'Sorted array:';
print_r($fruits);
?>
Output:
Original array: Array ([0] => lemon[1] => banana[2] => apple[3] => pear)
sorted array :Array ([0] => Lemon[1] => Pear[2] => Apple[3] => Banana)
3. asort -- Sort the array and maintain the index relationship
$fruits = array('a'=>'Lemon','b'=>'Banana','c'=>' Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '
';
asort($fruits);
echo 'Sorted array:';
print_r($fruits);
?>
output
Original array: Array ([a] => lemon[b] => banana[c] => apple[d] => pear)
Sorted array: Array ([a] => lemon[d] ] => Pear[c] => Apple[b] => Banana)
4. ksort -- Sort the array by key name
php
$fruits = array('b'=>'Lemon','a'=>'Banana','d'=>'Apple','c'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '
';
ksort($fruits);
echo 'Sorted Array: ';
print_r($fruits);
?>
output
Original array: Array ([b] => lemon[a] => ; Banana[d] => Apple[c] => Pear)
Sorted array: Array ( [a] => Banana[b] => Lemon[c] => Pear[d ] => Apple)
5. rsort -- Reverse sort the array
$fruits = array('Lemon','Banana' ,'apple','pear');
echo 'Original array:';
print_r($fruits);
echo '
';
rsort($fruits );
echo 'Sorted array:';
print_r($fruits);
?>
output
Original array: Array ( [0 ] => Lemon[1] => Banana[2] => Apple[3] => Pear)
Sorted array: Array ( [0] => Banana[1] => Apple[2] => Pear[3] => Lemon)
6. arsort -- Sort the array in reverse and maintain the index relationship
$fruits = array('a'=>'Lemon','b'=>'Banana','c'=>'Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '
';
arsort($fruits);
echo 'Sorted array :';
print_r($fruits);
?>
output
Original array: Array ([a] => Lemon[b] => Banana[c] => Apple[d] => Pear)
Sorted array: Array ( [b] => Banana[c] => Apple[d] => Pear[a] => Lemon)
7. krsort -- Sort the array in reverse order by key name
$fruits = array('a'=> ;'Lemon','b'=>'Banana','c'=>'Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '
';
krsort($fruits);
echo 'Sorted array:';
print_r($fruits);
?>
output
Original array: Array ([a] => lemon[b] => banana[c] => apple[d] => ; Pear)
Sorted array: Array ( [d] => Pear[c] => Apple[b] => Banana[a] => Lemon)
8. shuffle -- Shuffle the array
$fruits = array(' a'=>'Lemon','b'=>'Banana','c'=>'Apple','d'=>'Pear');
echo 'Original array:' ;
print_r($fruits);
echo '
';
shuffle($fruits);
echo 'Shuffled array:';
print_r( $fruits);
?>
output
Original array: Array ( [a] => Lemon[b] => Banana[c] => Apple [d] => Pear)
Shuffled array: Array ( [0] => Banana[1] => Apple[2] => Lemon[3] => Pear)
9. array_reverse -- Returns an array with the cells in reverse order
$fruits = array('a'=>'Lemon','b '=>'Banana','c'=>'Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '
';
$fruits = array_reverse($fruits);
echo 'Reversed array:';
print_r($fruits);
? >
output
Original array: Array ([a] => lemon[b] => banana[c] => apple[d] => pear)
Reversed array: Array ([d] => Pear[c] => Apple[b] => Banana[a] => Lemon)
10. array_unshift -- in array Insert one or more units at the beginning
$fruits = array('a'=>'Lemon','b'=>'Banana ','c'=>'Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '< br/>';
array_unshift($fruits,'杮子');
echo 'Array after insertion:';
print_r($fruits);
?>
output
Original array: Array ([a] => Lemon[b] => Banana[c] => Apple[d] => Pear)
After insertion Array: Array ([0] => 杮子[a] => lemon[b] => banana[c] => apple[d] => pear)
11. array_shift -- Move the unit at the beginning of the array out of the array
$fruits = array('a'=>'Lemon','b'=>'Banana ','c'=>'Apple','d'=>'Pear');
echo 'Original array:';
print_r($fruits);
echo '< br/>';
array_shift($fruits);
echo 'Array after shifting:';
print_r($fruits);
?>
output
Original array: Array ([a] => lemon[b] => banana[c] => apple[d] => pear)
The moved array: Array ( [b] => Banana [c] => Apple [d] => Pear)
12. array_rand -- Randomly remove one or more units from the array
$fruits = array ('Lemon', 'Banana', 'Apple', 'Pear' );
echo 'Original array:';
print_r ( $fruits );
echo '
';
$newArr_key = array_rand ( $fruits, 2 );
echo 'Array after randomization:';
echo $fruits [$newArr_key [0]].' ';
echo $fruits [$newArr_key [1]];
?>
output
Original array: Array ( [0] => Lemon[1] => Banana[2] => Apple[3] => Pear)
Random array: pear apple
13. array_pop -- Pop the last unit of the array (Pop)
$fruits = array ('lemon', 'banana', 'apple', 'pear' );
echo 'Original array:';
print_r ( $fruits );
echo '
';
array_pop ( $fruits );
echo 'Array after popping:';
print_r ( $fruits );
?>
Output:
Original array: Array ([0] => Lemon[1] => Banana[2] => Apple[3] => Pear)
Array after popping :Array ([0] => Lemon[1] => Banana[2] => Apple)
14. array_push -- Push one or more cells to the end of the array (push)
$fruits = array ('Lemon', 'Banana', 'Apple', 'Pear' );
echo 'Original array:' ;
print_r ( $fruits );
echo '
';
array_push ( $fruits,'杮子');
echo 'Array after popping:';
print_r ( $fruits );
?>
Output:
Original array: Array ( [0] => Lemon[1] => Banana[2 ] => Apple[3] => Pear)
Array after popping up: Array ([0] => Lemon[1] => Banana[2] => Apple[3] => Pear[4] => 杮子)
5. Array pointer operations
each -- Returns the current key/value pair in the array and moves the array pointer forward one step
current -- Returns the current unit in the array
reset -- Moves the internals of the array The pointer points to the first unit
end -- points the internal pointer of the array to the last unit
next -- moves the internal pointer in the array forward one bit
pos -- alias of current()
prev -- Rewind the internal pointer of the array by one bit
$fruits = array ('lemons', 'banana', 'apple' , 'Pear' );
print_r ( $fruits );
echo '
';
echo 'each() : ';
print_r ( each ( $fruits ) ) ;
echo '
';
echo 'current() : ';
echo (current ( $fruits ));
echo '
';
echo 'next() : ';
echo (next ( $fruits ));
echo '
';
echo 'end() : ';
echo (end ( $fruits ));
echo '
';
echo 'prev() : ';
echo (prev ( $fruits ));
echo '
';
echo 'pos() : ';
echo (pos ( $fruits ));
echo '
';
?>
Output:
Array ( [0] => Lemon[1] => Banana[2] => Apple[3] => Pear)
each( ) : Array ( [1] => lemon[value] => lemon[0] => 0 [key] => 0 )
current() : banana
next() : apple
end() : Pear
prev() : Apple
pos() : Apple
6. Count the number of arrays
count -- Count the number of cells in the array or the number of attributes in the object
sizeof -- Alias of count()
array_count_values -- Count the number of occurrences of all values in the array
$nums = array (1, 3, 5, 1 , 3, 4, 5, 65, 4, 2, 2, 1, 4, 4, 1, 1, 4, 1, 5, 4, 5, 4 );
echo count ( $nums );
echo '
';
echo sizeof ( $nums );
echo '
';
$arrayCount = array_count_values ( $nums );
print_r ( $arrayCount ) ;
?>
output
22
22
Array ( [1] => 6 [3] => 2 [5] => 4 [4] => 7 [65] => 1 [2] => 2 )
Seven. Convert the array into a scalar variable: extract()
Convert each element in the array into a variable. The variable name is the key of the array element, and the variable value is the value of the array element.
$fruits = array('a'=>'apple','b'=> 'banana','o'=>'orange');
extract($fruits);
echo $a.'
';
echo $b.'
';
echo $o.'
';
?>
output
apple
banana
orange

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
