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:

1

2

3

4

5

6

7

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

1

2

3

4

<?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

1

2

3

4

5

6

7

8

<?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

1

2

3

4

5

6

7

<?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:

1

2

3

4

5

6

7

<?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:

1

2

3

4

5

6

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?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.

1

2

3

4

5

6

7

8

9

10

11

<?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.

1

2

3

4

5

6

7

8

9

10

11

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

<?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.

1

2

3

4

5

6

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

$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:

1

2

3

4

5

6

7

8

9

10

11

$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:

1

2

3

4

5

6

7

8

9

10

11

$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:

1

2

3

4

5

6

7

8

9

10

11

$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:

1

2

3

4

5

6

7

8

9

10

11

$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:

1

2

3

4

5

6

7

8

9

10

$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:

1

2

3

4

$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:

1

2

3

4

$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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

1

2

3

4

5

6

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
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 and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles