Table of Contents
Overview
Create
Traversal
1. for Loop
2. while Loop
3. foreach Loop
Operation key or value
Sort
Stack and queue
Split, fill, merge
Other functions
Home Backend Development PHP Tutorial PHP&&& Array - CSDN Blog

PHP&&& Array - CSDN Blog

Apr 03, 2018 am 10:53 AM
php blog

This article introduces array issues in PHP. Now I share it with you. It can also be a reference for friends in need. Let’s take a look together.

Overview

We know that in the PHP programming language, arrays are used very frequently and are used in almost every script. PHP comes with a large number of excellent functions for operating arrays for our use. This article will classify and summarize the use of these array functions for your convenience in the future.

Create

1. range()

Create an array with a specified range:

$arr1 = range(0, 10);     # array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)$arr2 = range(0, 10, 2);  # array(0, 2, 4, 6, 8, 10)$arr3 = range('a', 'd');  # array('a', 'b', 'c', 'd')$arr4 = range('d', 'a');  # array('d', 'c', 'b', 'a')
Copy after login
2. compact ()

Create an array containing variable names and their values:

$number = 10;
$string = "I'm PHPer";
$array  = array("And", "You?");
$result = compact("number", "string", "array"); # array('number'=>10, 'string'=>"I'm PHPer", 'array'=>array("And", "You?"))
Copy after login
3. array_combine()

Create an array with an An array with the value as its key and the value of another array as its value:

$key    = array("1", "3", "5", "7", "9");
$value  = array("I", "Am", "A", "PHP", "er");
$result = array_combine($number,$array);     # array('1'=>I, '3'=>'Am', '5'=>'A', '7'=>'PHP', '9'=>'er')
Copy after login

Traversal

1. for Loop
$arr = range(0, 10);for($i = 0; $i < count($arr);  $i++) {    echo $arr[$i];
}
Copy after login
Disadvantages: Only indexed arrays can be traversed.
2. while Loop
$products = array(&#39;apple&#39;=>3, 'milk'=>6, 'eggs'=>10);while(list($product, $quantity) = each($products)) {    echo $product . '-' . $quantiry;
}
Copy after login
Disadvantage: After the traversal is completed, the array cannot be traversed for the second time (the internal pointer of the array points to the last element).
3. foreach Loop
$products = array('apple'=>3, 'milk'=>6, 'eggs'=>10);foreach($products as $product => $quantity) {    echo $product . '-' . $quantiry;
}
Copy after login

Operation key or value

unset() — Delete array members or arrays
in_array() — Check whether a certain value exists in the array
array_key_exists() — Check whether the given key name or index exists in the array
array_search() — Searches for a given value in the array, and returns the corresponding key name if successful

$array = array(1, 2, 3);unset($array); # array()$fruit = array('apple' => 'goold','orange' => 'fine','banana' => 'OK');if(in_array('good', $fruit)) {    echo 'Exit';
}

$search_array = array('first' => 1, 'second' => 4);if (array_key_exists('first', $search_array)) {    echo "Exit";
}

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); # $key = 2;
Copy after login

array_keys() — Returns some or all of the keys in the array Key name
array_values() — Returns all values ​​in the array

$array  = array('apple'=>'good', 'orange'=>'fine', 'banana'=>'ok');
$keys   = array_keys($array);   # array('apple', 'orange', 'banana')$values = array_values($array); # array('good', 'fine', 'ok')
Copy after login

array_unique() — Removes duplicate values ​​from the array

$input  = array(4, '4', '3', 4, 3, '3');
$result = array_unique($input); # array(4, '3')
Copy after login

array_flip() — Swap the keys and values ​​in the array

$input  = array('oranges', 'apples', 'pears');
$result = array_flip($input); # array('oranges'=>0, 'apples'=>1, 'pears'=>2)
Copy after login

array_count_values() Count all the values ​​in the array

$input  = array(1, 'hello', 1, 'world', 'hello');
$result = array_count_values($input); # array('1'=>2, 'hello'=>2, 'world'=>1)
Copy after login

Sort

1. sort() and rsort()

Sort the array in ascending or descending order:

$fruits = array();
sort($fruits);  # array('apple', 'banana', 'lemon', 'orange')rsort($fruits); # array('orange', 'lemon', 'banana', 'apple')
Copy after login
2. asort() and arsort()

Sort associative arrays (by element value) in ascending or descending order and maintain index relationships:

$fruits = array('d'=>'lemon', 'a'=>'orange', 'b'=>'banana', 'c'=>'apple');
asort($fruits);  # array('c'=>''apple', 'b'=>''banana', 'd'=>'lemon', 'a'=>'orange')arsort($fruits); # array('a'=>'orange', 'd'=>'lemon', 'b'=>''banana', 'c'=>''apple')
Copy after login
3. ksort()

Sort the array by key name:

$fruits = array('d'=>'lemon', 'a'=>'orange', 'b'=>'banana', 'c'=>'apple');
ksort($fruits); # array('a'=>'orange', 'b'=>'banana', 'c'=>'apple', 'd'=>'lemon')
Copy after login
4. shuffle()

Randomly shuffle Random array sorting:

$numbers = range(1, 5);
shuffle($numbers); # array(3, 2, 5, 1, 4)
Copy after login

Stack and queue

array_push() — Push one or more elements to the end of the array (push)
array_pop() — Pop the last unit of the array off the stack

$stack = array('orange', 'banana');

array_push($stack, 'apple", 'raspberry'); # array('orange', 'banana', 'apple', 'raspberry')

$fruit = array_pop($stack);  #array('orange', 'banana', 'apple')
Copy after login

array_unshift() — Insert one or more units at the beginning of the array
array_shift() — Move the cells at the beginning of the array out of the array

$queue = array('orange', 'banana');

array_unshift($queue, 'apple", 'raspberry'); # array('apple', 'raspberry', 'orange', 'banana')

$fruit = array_shift($queue); # array('raspberry', 'orange', 'banana')
Copy after login

Split, fill, merge

array_slic() — Remove a segment from the array
array_splice() — Remove part of an array and replace it with another value

$input  = array('a', 'b', 'c', 'd', 'e');
$result = array_slice($input, 2); # array('c', 'd', 'e')$input = array('red', 'green', 'blue', 'yellow');
array_splice($input, 2, 1); # array('red', 'green', 'yellow')
Copy after login

array_pad() — Fill an array with a value of the specified length

$input  = array(12, 10, 9);
$result = array_pad($input, 5, 0);   # array(12, 10, 9, 0, 0)$result = array_pad($input, -7, -1); # array(-1, -1, -1, -1, 12, 10, 9)
Copy after login

array_fill() — Fills an array with the given values ​​

$a = array_fill(5, 3, 'a');     # array(5=>'a', 6=>'a', 7=>'a')$b = array_fill(-2, 3, 'pear'); # array(-2=>'a', 0=>'a', 1=>'a')
Copy after login

array_fill_keys() — Fills the array with the specified keys and values ​​

$keys   = array('foo', 5, 10, 'bar');
$result = array_fill_keys($keys, 'a'); # array('foo'=>'a', 5=>'a', 10=>'a', 'bar'=>'a')
Copy after login

array_merge() — Merge one or more arrays

$array1 = array('data0');
$array2 = array('data1');
$result = array_merge($array1, $array2); # array('data0', 'data1')
Copy after login

Other functions

1. array_walk()

Use a user-defined function to perform callback processing on each element in the array (change the original array):

$a = array(1, 2, 3, 4, 5);
array_walk($a, function(&$value, $key) {
    ++$value;
}); # array(2, 3, 4, 5, 6)
Copy after login
2. array_map()

Apply the callback function to On the cells of the given array (the original array is not changed, and a new array is generated as the result):

$a = array(1, 2, 3, 4, 5);
$b = array_map(function($item) {    return $item + 1;
}, $a); # array(2, 3, 4, 5, 6)
Copy after login
3. array_rand()

Randomly taken from the array One or more elements:

$input  = array('apple', 'banana', 'lemon', 'orange');
$result = array_rand($input, 2); # array('banana', 'lemon')
Copy after login
4. array_diff()

Calculate the difference of array value:

$array1 = array('a' => 'green', 'red', 'blue', 'red');
$array2 = array('b' => 'green', 'yellow', 'red');
$result = array_diff($array1, $array2); # array('blue')
Copy after login

Related recommendations:

Simple arrangement of PHP arrays

Detailed explanation of PHP array functions

             

The above is the detailed content of PHP&&& Array - CSDN Blog. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

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

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

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

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles