search
HomeBackend DevelopmentPHP TutorialPHP learning summary array
PHP learning summary arrayApr 03, 2018 pm 04:29 PM
phpSummarizearray

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')
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?"))
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')

Traversal

1. for Loop
$arr = range(0, 10);
for($i = 0; $i <blockquote>Disadvantages: Only indexed arrays can be traversed. </blockquote><h5 id="code-while-code-Loop">2. <code>while</code> Loop</h5><pre class="brush:php;toolbar:false">$products = array('apple'=>3, 'milk'=>6, 'eggs'=>10);
while(list($product, $quantity) = each($products)) {
    echo $product . '-' . $quantiry;
}
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;
}

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;

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')

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

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

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)

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)

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')
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')
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')
4. shuffle()

Randomly shuffle Random array sorting:

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

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')

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')

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')

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)

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')

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')

array_merge() — Merge one or more arrays

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

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)
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)
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')
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')

Related recommendations:

PHP Learning Summary Variable

PHP Learning Summary String                                      

The above is the detailed content of PHP learning summary array. For more information, please follow other related articles on the PHP Chinese website!

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.