search
HomeBackend DevelopmentPHP TutorialSummary of examples of commonly used array array functions in PHP [assignment, splitting, merging, calculation, adding, deleting, querying, judging, sorting]

The examples in this article summarize the commonly used array array functions in PHP. Share it with everyone for your reference, the details are as follows:

array_combine

Function: Use the value of one array as the key name of the new array, and the value of the other array as the value of the new array

Case:

<?php
$a = array("one","two","three");
$b = array("一","二","三");
$c = array_combine($a,$b);
print_r($c);
/**结果
*Array ( [one] => 一 [two] => 二 [three] => 三 )
*/

array_chunk

Function: split the array into multiple arrays

<?php
$input_array = array("a"=>"apple","b"=>"blue","c","d","e");
echo "<pre class="brush:php;toolbar:false">";
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2,True));
echo "
"; /**结果 Array (  [0] => Array   (    [0] => apple    [1] => blue   )  [1] => Array   (    [0] => c    [1] => d   )  [2] => Array   (    [0] => e   ) ) Array (  [0] => Array   (    [a] => apple    [b] => blue   )  [1] => Array   (    [0] => c    [1] => d   )  [2] => Array   (    [2] => e   ) ) */

array_count_values

Function: Count the number of times a value appears in an array

<?php
$input_array = array("a"=>"apple","b"=>"blue","c","d","e");
echo "<pre class="brush:php;toolbar:false">";
print_r(array_count_values($input_array));
echo "
"; /**结果 Array (  [apple] => 1  [blue] => 1  [c] => 1  [d] => 1  [e] => 1 ) */

array_diff

Function: Remove the data in the second array from the first array and return the remaining content as the result

<?php
$array1 = array("a"=>"apple","b"=>"blue","c","d","e");
$array2 = array("apple","c","d","f");
$result = array_diff($array1, $array2);
$result2 = array_diff($array2, $array1);
echo "<pre class="brush:php;toolbar:false">";
print_r($result);//数组1中去掉数组2中剩下的
print_r($result2);//数组2中去掉数组1中剩下的
echo "
"; /**结果 Array (  [b] => blue  [2] => e ) Array (  [3] => f ) */

array_map

Function: Execute the callback function into the array

<?php
//定义回调函数
function cube($n){
 return ($n*$n*$n);
}
$a = array(1,2,3,4,5);
$b = array_map("cube",$a);
echo "<pre class="brush:php;toolbar:false">";
print_r($b);
echo "
"; /**结果 Array (  [0] => 1  [1] => 8  [2] => 27  [3] => 64  [4] => 125 ) */

array_merge

Function: Merge one or more arrays

Note: If there are keys with the same key names at the back, the previous content will be overwritten, and the key names with numbers will be added to the back

<?php
$array1 = array("color"=>"red",2,4);
$array2 = array("a","b","color"=>"green","shape"=>"trapezoid",4);
$result1 = array_merge($array1,$array2);
$result2 = array_merge_recursive($array1,$array2);
echo "<pre class="brush:php;toolbar:false">";
print_r($result1);
print_r($result2);
echo "
"; /**结果 Array (  [color] => green  [0] => 2  [1] => 4  [2] => a  [3] => b  [shape] => trapezoid  [4] => 4 ) Array (  [color] => Array   (    [0] => red    [1] => green   )  [0] => 2  [1] => 4  [2] => a  [3] => b  [shape] => trapezoid  [4] => 4 ) */

array_pop

Function: Remove the last element of the array and return the content of the removed element

<?php
$stack = array("orange","banana","apple","1");
$last = array_pop($stack);
echo "<pre class="brush:php;toolbar:false">";
print_r($stack);
print_r($last);
echo "
"; /**结果 Array (  [0] => orange  [1] => banana  [2] => apple ) 1 */

array_push

Function: Push multiple units into At the end of the array, return the number of arrays after

<?php
$stack = array("orange","banana");
$count = array_push($stack,"apple","red","blue");
echo "<pre class="brush:php;toolbar:false">";
print_r($stack);
print_r($count);
echo "
"; /**结果 Array (  [0] => orange  [1] => banana  [2] => apple  [3] => red  [4] => blue ) 5 */

array_rand

Function: Get a random key name

<?php
$input = array("orange","banana","apple","red","blue");
$rand = array_rand($input,2);;
print_r($rand);
$rand = array_rand($input,3);
print_r($rand);
/**结果
Array
(
 [0] => 1
 [1] => 4
)
Array
(
 [0] => 0
 [1] => 1
 [2] => 3
)
*/

array_search

Function: Query the content in the array and return the key value. If there are multiple matches, return the first matching content

<?php
$array = array("blue"=>"b","red"=>"r","green","r");
$key = array_search(&#39;b&#39;, $array);
echo $key;
echo "<br>";
$key = array_search(&#39;r&#39;, $array);
echo $key;
echo "<br>";
/**结果
blue
red
*/

array_shift

Function: Remove the starting elements, opposite to array_pop

<?php
$fruit = array("milk","orange","banana","apple");
$top = array_shift($fruit);
print_r($top);
echo "<br>";
print_r($fruit);
/**结果
milk
Array ( [0] => orange [1] => banana [2] => apple )
*/

array_unique

Function: Remove duplicate elements from the array and retain the first one, including key name and value

<?php
$input = array("a"=>"green","red","b"=>"green","blue","c"=>"red");
$result = array_unique($input);
print_r($result);
echo "<br>";
print_r($input);
/**结果
Array ( [a] => green [0] => red [1] => blue )
Array ( [a] => green [0] => red [b] => green [1] => blue [c] => red )
*/

array_slice

Function: From the array Take out some elements

<?php
$input = array("a","b","c","d","e");
$output = array_slice($input,2);//第二个参数没有时,表示取到最后一个元素
print_r($output);
echo "<br>";
$output = array_slice($input,-2,1);//第二个参数是正数时,表示个数;倒数第一个是-1,倒数第二个是-2
print_r($output);
echo "<br>";
$output = array_slice($input,0,3);
print_r($output);
echo "<br>";
$output = array_slice($input,2,-1);//第二个参数是负数时,表示位置,取到哪一位,不包括本身
print_r($output);
echo "<br>";
$output = array_slice($input,2,-1,true);//第三个参数为true时,保留原有的键值
print_r($output);
echo "<br>";
/**结果
Array ( [0] => c [1] => d [2] => e )
Array ( [0] => d )
Array ( [0] => a [1] => b [2] => c )
Array ( [0] => c [1] => d )
Array ( [2] => c [3] => d )
*/

count

Function: Return the number of array elements. If the element is an array, it is counted as one

<?php
$input = array("a","b","c",array("d","e"));
$count = count($input);
echo $count;
echo "<br>";
$input = array("a","b","c","d","e");
$count = count($input);
echo $count;
/**结果
4
5
*/

current

Function: Get the current pointer pointing to the element

<?php
$array = array("foot","bike","car","plane");
$result = current($array);
echo $result."<br>";
next($array);//使指针指向下一个元素
$result = current($array);
echo $result."<br>";
prev($array);//使指针指向前一个元素
$result = current($array);
echo $result."<br>";
end($array);//使指针指向最后一个元素
$result = current($array);
echo $result."<br>";
/**结果
foot
bike
foot
plane
*/

in_array

Function: Check whether a certain value exists in the array, return True if not, return False

<?php
$os_list = array("Mac","NT","Irix","Linux");
if(in_array("Irix",$os_list)){
 echo "当前操作系统列表中存在Irix";
}else{
 echo "当前操作系统列表中不存在Irix";
}
echo "<br>";
if(in_array("mac",$os_list)){
 echo "当前操作系统列表中存在mac";
}else{
 echo "当前操作系统列表中不存在mac";
}
echo "<br>";
/**结果
当前操作系统列表中存在Irix
当前操作系统列表中不存在mac
*/

list

Function: convert the array Assign the information in to multiple variables

<?php
$info = array("red","blue","green");
list($flag,$sky,$grassland) = $info;
echo "$flag,$sky,$grassland";
echo "<br>";
list($flag,,$grassland) = $info;
echo "$flag,$grassland";
echo "<br>";
list(,,$grassland) = $info;
echo "$grassland";
echo "<br>";
/**结果
red,blue,green
red,green
green
*/

shuffle

Function: shuffle the array

<?php
$numbers = range(1,5);//生成一个随机数组
print_r($numbers);
echo "<br/>";
shuffle($numbers);//打乱数组
print_r($numbers);
/**结果
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Array ( [0] => 4 [1] => 1 [2] => 5 [3] => 2 [4] => 3 )
*/

array_keys

Function: Get the key name of the array, the second parameter can specify to get an element

<?php
$array = array(0=>100,"color"=>"red");
print_r(array_keys($array));
echo "<br>";
$array = array("blue","red","green","blue","blue");
print_r(array_keys($array,"blue"));
echo "<br>";
$array = array("color"=>array("blue","red","green"),"size"=>array("small","medium","large"));
print_r(array_keys($array));
echo "<br>";
/**结果
Array ( [0] => 0 [1] => color )
Array ( [0] => 0 [1] => 3 [2] => 4 )
Array ( [0] => color [1] => size )
*/

array_reverse

Function: Get the reverse of the array

<?php
$input = array("php",3.0,array("green","red"));
$result = array_reverse($input); //打乱键名
$result_keyed = array_reverse($input,TRUE);//保留键名
print_r($result);
print_r($result_keyed);
/**结果
Array
(
 [0] => Array
  (
   [0] => green
   [1] => red
  )
 [1] => 3
 [2] => php
)
Array
(
 [2] => Array
  (
   [0] => green
   [1] => red
  )
 [1] => 3
 [0] => php
)
*/

arsort

Function: Reverse sorting, the index remains unchanged

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
arsort($fruits);//按照字符逆向排序或数字
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
b = orange
a = lemon
c = banana
d = apple
*/

##asort

Function: Forward sorting

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
arsort($fruits);//按照字符逆向排序或数字
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
echo "<p>";
asort($fruits);//按照字符正向排序或数字
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
b = orange
a = lemon
c = banana
d = apple
d = apple
c = banana
a = lemon
b = orange
*/

krsort

Function: Reverse sorting by key name

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
krsort($fruits);//按照键名逆向排序或数字
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
d = apple
c = banana
b = orange
a = lemon
*/

ksort

Function: Forward sorting by key name

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
ksort($fruits);//按照键名正向排序或数字
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
a = lemon
b = orange
c = banana
d = apple
*/

rsort

Function: reverse sorting by value, key name change

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
rsort($fruits);//按照值进行逆向排序或数字,键名改变
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
0 = orange
1 = lemon
2 = banana
3 = apple
*/

sort

Function: Forward sorting by value, key name change

<?php
$fruits = array(
 "a"=>"lemon",
 "b"=>"orange",
 "c"=>"banana",
 "d"=>"apple",
 );
sort($fruits);//按照值进行逆向排序或数字,键名改变
foreach($fruits as $key=>$val){
 echo "$key = $val<br>";
}
/**结果
0 = apple
1 = banana
2 = lemon
3 = orange
*/

I hope this article will help everyone in PHP programming design help.

For more examples of commonly used array array functions in PHP [assignment, splitting, merging, calculating, adding, deleting, querying, judging, sorting] please pay attention to the PHP Chinese website for related articles!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.