Home Backend Development PHP Tutorial PHP array function knowledge summary_php skills

PHP array function knowledge summary_php skills

May 16, 2016 am 08:59 AM
php function array

This article shares the basic knowledge of PHP array functions for your reference. The specific content is as follows

Array array is a very important data type. Compared to other data types, it is more like a structure, and this structure can store a series of values. Arrays can store many values ​​in a single variable name, and a value can be accessed by referencing a subscript.
In PHP, there are three array types:
indexed array - array with numeric index
Associative array - array with specified keys
Multidimensional array - an array containing one or more arrays

1. Create an array

array(key => value)

1. Create an index array

Use the array() function to declare an array. PHP is a weakly typed language that is relatively flexible and convenient. It can also be the element value of the array directly. There is no need for a key value. The index is automatically assigned (the index starts from 0).
example:

array("1" => "Baidu","2" => "Alibaba","3" => "Tencent");
Or not using key values:
array("Baidu","Alibaba","Tencent");
Of course it can also be written as:
$arr[0] = "Baidu";
$arr[1] = "Ali";
$arr[2] = "Tencent";
Copy after login

2. Create an associative array

Associative arrays are similar to index arrays, except that associative arrays cannot only be numbers like the key names of index arrays. They can be numerical values, strings, and mixed forms. The basis for determining whether an array is an associative array is: Array Whether there is a key name in that is not a number. No, it's related.

array("Robin Li" => "Baidu","Jack Ma" => "Alibaba","Ma Huateng" => "Tencent");

3. Multidimensional array

array(array(),array()) two-dimensional array

Get the length of the array - count() function

<?php
$arr = array("Baidu","Alibaba","Tencent");
echo count($arr);
?> //The result returns 3 (indicating that there are three elements in the array)

Copy after login

2. Traverse the array

Output the value of the element in the array. For index arrays, for and foreach are commonly used; for associative arrays, foreach is commonly used. Use the print_r() function to print the results after the loop, or var_dump().

1. Traverse the index array

Traverse and output all values ​​of the index array, you can use for, foreach(array_expression as value), foreach(arrayexpressionaskey => $value) loop, as follows:

Use for loop

<?php
$arr = array("Baidu","Alibaba","Tencent");
$arrlen = count($arr);//Get the length of the array
for ($i=0; $i <$arrlen ; $i ) {
  $data[] = $arr[$i];
}
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($data);
Copy after login

The print result is displayed as follows:
Array
(
[0] => Baidu
[1] => Ali
[2] => Tencent
)
Using foreach loop

<?php
$arr = array("Baidu","Alibaba","Tencent");
foreach ($arr as $value) {
  $data[] = $value;
}
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($data);//The print result is the same as above
Copy after login

Note: There is an array symbol [] after data. Why?

2. Traverse associative array

Traverse and output all values ​​of the associative array, you can use the foreach (array_expression as key=>value) loop, as follows:

<?php
$arr = array("Robin Li" => "Baidu","Jack Ma" => "Alibaba","Ma Huateng" => "Tencent");
foreach ($arr as $key => $value) {
  $data[$key] = $value;
}
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($data);
Copy after login

The print result shows:

Array
(
  [Robin Li] => Baidu
  [Jack Ma] => Ali
  [Ma Huateng] => Tencent
)
Copy after login

Did you notice? At this time, what is after data is [$key]? instead of []
One is a numeric associative array and the other is a numeric index array,

3. Add and delete elements of the array

Add
to the end of the array element The array_push(array,value1,value2…) function adds one or more elements (push) to the end of the array of the first parameter and returns the length of the new array.
This function is equivalent to multiple calls to array[]=value.

<?php
$arr = array("Baidu","Alibaba","Tencent");
array_push($arr,"Zhihu","Weibo");
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($arr);
//Print result shows:
Array
(
  [0] => Baidu
  [1] => Ali
  [2] => Tencent
  [3] => Zhihu
  [4] => Weibo
)

Copy after login

Add at the beginning of the array element
The array_unshift(array,value1,value2,value3…) function is used to insert new elements into the array. The values ​​of the new array will be inserted at the beginning of the array.

<?php
$arr = array("Baidu","Alibaba","Tencent");
array_unshift($arr,"Zhihu","Weibo");
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($arr);
//Print result shows:
Array
(
  [0] => Zhihu
  [1] => Weibo
  [2] => Baidu
  [3] => Ali
  [4] => Tencent
)

Copy after login

Delete at the end of the array element
The array_pop(array) function removes the last element from the array.

<?php
$arr = array("Baidu","Alibaba","Tencent");
array_pop($arr);
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($arr);
The print result shows:
Array
(
  [0] => Baidu
  [1] => Ali
)

Copy after login

Delete at the beginning of the array element
The array_shift(array) function deletes the first element in the array and returns the value of the deleted element.

<?php
$arr = array("Baidu","Alibaba","Tencent");
array_shift($arr);
echo "<pre class="brush:php;toolbar:false">"; //Newline display
print_r($arr);
The print result shows:
Array
(
  [0] => Ali
  [1] => Tencent
)

Copy after login

Remove duplicate values ​​from the array
The array_unique(array) function removes duplicate values ​​from an array and returns the resulting array.

<?php
$arr = array("Baidu","Alibaba","Tencent","Baidu","Weibo");
$data = array_unique($arr);
echo "<pre class="brush:php;toolbar:false">";
print_r($data);
The print result shows:
Array
(
  [0] => Baidu
  [1] => Ali
  [2] => Tencent
  [4] => Weibo
)

Copy after login

4. Positioning array elements

Search for values ​​present in the array
in_array(search,array,type) checks whether the specified value exists in the array.
Returns true if the given value search exists in the array array. If the third parameter is set to true, the function returns true only if the element exists in the array and has the same data type as the given value. If the parameter is not found in the array, the function returns false.

<?php
$arr = array("Baidu","Alibaba","Tencent");
while (in_array("Baidu", $arr)) {
  echo "already found";
  break;
} //Output has been found

Copy after login

Retrieve a value from the array based on conditions: array_slice(array,start,length,preserve)
start is required. numerical value. Specifies the starting position of the element to be retrieved. 0 = first element.
If the value is set to a positive number, it will be taken from front to back.
If the value is set to a negative number, the absolute value of start is taken from back to front. -2 means start from the second to last element of the array.

length Optional. numerical value. Specifies the length of the returned array.
If the value is set to an integer, that number of elements is returned.
If this value is set to a negative number, the function will terminate fetching this far from the end of the example array.
If this value is not set, all elements starting from the position set by the start parameter to the end of the array are returned.

<?php
$arr = array("Baidu","Alibaba","Tencent","Zhihu","Weibo");
$data = array_slice($arr,0,4);
echo "<pre class="brush:php;toolbar:false">";
print_r($data);
The print result shows:
Array
(
  [0] => Baidu
  [1] => Ali
  [2] => Tencent
  [3] => Zhihu
)

Copy after login

array_splice(array,start,length,array) function removes the selected element from an array and replaces it with a new element. This function will also return the array containing the removed elements.

<?php
$arr1 = array("Baidu","Alibaba","Tencent");
$arr2 = array("Zhihu","Weibo");
array_splice($arr1,0,2,$arr2);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr1);
The print result shows:
Array
(
  [0] => Zhihu
  [1] => Weibo
  [2] => Tencent
)

Copy after login

5. Array merging, splitting and comparison

The array_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter and is appended in the order in which subsequent array parameters appear.

<?php
$arr1 = array("Baidu","Alibaba","Tencent");
$arr2 = array("Zhihu","Weibo");
$data = array_merge($arr1,$arr2);
echo "<pre class="brush:php;toolbar:false">";
print_r($data);
The print result shows:
Array
(
  [0] => Baidu
  [1] => Ali
  [2] => Tencent
  [3] => Zhihu
  [4] => Weibo
)

Copy after login

Append array recursively
The array_merge_recursive() function is the same as array_merge() and can merge two or more arrays together to form a combined array. The difference between the two is that the function takes a different approach when a key in an input array is already present in the result array. array_merge() overwrites the previously existing key/value pairs and replaces them with the key/value pairs in the current input array, while array_merge_recursive() merges the two values ​​together to form a new array with the original keys as an array name. Its form is:

$arr= array('one'=>'C', 'one'=>'B');
$arr1= array('three'=>'1', 'one'=>'2');
$arr2= array_merge_recursive($arr, $arr1);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr2);
The print result shows:
Array
(
  [one] => Array
    (
      [0] => B
      [1] => 2
    )

  [three] => 1
)

Copy after login

Merge two arrays
The array_combine() function will generate a new array, which consists of a set of submitted keys and corresponding values, in the form:

$arr= array('A', 'B');
$arr1= array('1', '2');
$arr2= array_combine($arr, $arr1);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr2);
The print result shows:
Array
(
  [A] => 1
  [B] => 2
)

Copy after login

Find the intersection of arrays
The array_intersect() function returns a key-preserved array consisting only of values ​​that appear in the first array and appear in every other input array. Its form is as follows:

$arr= array('A', 'B', 'C', 'D');
$arr1= array('A', 'B', 'E');
$arr2= array('A', 'F', 'D');
$arr3= array_intersect($arr, $arr1, $arr2);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr3);
The print result shows:
Array
(
  [0] => A
)

Copy after login

Note: array_intersect() will consider two elements equal only if they have the same data type.

Find the intersection of associative arrays
array_intersect_assoc() is basically the same as array_intersect(), except that it also considers the keys of the array in the comparison. Therefore, only key/value pairs that appear in the first array and also appear in all other input arrays are returned in the result array. Its form is as follows:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');
$arr1= array('a'=>'A', 'c'=>'B', 'E');
$arr2= array('a'=>'A', 'b'=>'F', 'd'=>'B');
$arr3= array_intersect_assoc($arr, $arr1, $arr2);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr3);
The print result shows:
Array
(
  [a] => A
)

Copy after login

Find the difference set of associative arrays
The function array_diff_assoc() is basically the same as array_diff(), except that it also takes into account the keys of the arrays when comparing, so key/value pairs that only appear in the first array and not in other input arrays will be returned. in the result array. Its form is as follows:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');
$arr1= array('a'=>'A', 'b'=>'B', 'e'=>'E');
$arr3= array_diff_assoc($arr, $arr1);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr3);
The print result shows:
Array
(
  [c] => C
  [d] => D
)

Copy after login

Other useful array functions
Returns a random set of keys The array_rand() function will return one or more keys in an array. Its form is:

$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');
$arr1= array_rand($arr, 2);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr1);
The print result shows:
 Array
(
  [0] => c
  [1] => d
) //The results displayed are different every time you refresh

Copy after login

Sum the values ​​in the array
The array_sum() function adds all the values ​​in the array together and returns the final sum, which has the following form:

$arr= array('A', 32, 12, 'B');
$count= array_sum($arr);
echo "<pre class="brush:php;toolbar:false">";
print_r($count);
Copy after login

The print result shows:
44

If the array contains other data types (such as strings), these values ​​will be ignored.

Divide array
The array_chunk() function decomposes the array into a multi-dimensional array, which consists of multiple arrays containing size elements. Its form is as follows:

$arr= array('A', 'B', 'C', 'D');
$arr1= array_chunk($arr, 2);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr1);
Copy after login

The print result shows:

Array
(
  [0] => Array
    (
      [0] => A
      [1] => B
    )

  [1] => Array
    (
      [0] => C
      [1] => D
    )

)

Copy after login

The functions that can be called when processing arrays are

array_filter(*array*,*callbackfunction*);
array_intersect_uassoc(*array1*,*array2*,*array3*...,*myfunction*)
array_intersect_ukey(*array1*,*array2*,*array3*...,*myfunction*)
array_reduce(*array*,*myfunction*,*initial*)
array_walk(*array*,*myfunction*,*userdata*...)
……
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone in learning PHP programming.

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles