Home Backend Development PHP Tutorial Detailed explanation of commonly used array operation methods in PHP

Detailed explanation of commonly used array operation methods in PHP

Jun 02, 2018 am 11:04 AM
php operate method

PHP has a traditional array array structure, and it is constantly improving with version upgrades. For example, from php5.4 onwards, you can use short array definition syntax, which we will talk about in this article. Let’s take a look at what is commonly used in PHP. Notes on array operation methods:

OverviewTo access the contents of a variable, you can use its name directly. If the variable is an array, its contents can be accessed using a combination of the variable name and a keyword or index.
Like other variables, the contents of array elements can be changed using operator =. Array cells can be accessed via the array[key] syntax.

2016516180436478.jpg (800×231)

Basic operations of arrays
php defines arrays:

<?php 
  $array = array(); 
  $array["key"] = "values"; 
?>
Copy after login

There are two main ways to declare arrays in PHP :

1. Use the array() function to declare the array,
2. Directly assign values ​​to the array elements.

<?php
  //array数组
  $users = array(&#39;phone&#39;,&#39;computer&#39;,&#39;dos&#39;,&#39;linux&#39;);
  echo $users;//只会打印出数据类型Array
  print_r($users);//Array ( [0] => phone [1] => computer [2] => dos [3] => linux )

  $numbers = range(1,5);//创建一个包含指定范围的数组
  print_r($numbers);//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
  print_r(true);//1
  var_dump(false);//bool(false)

//print_r可以把字符串和数字简单地打印出来,数组会以Array开头并已键值形式表示,print_r输出布尔值和null的结果没有意义,因此用var_dump更合适

//通过循环来显示数组里所有的值
  for($i = 0 ;$i < 5;$i++){
    echo $users[$i];
    echo &#39;<br/>&#39;;
  }

//通过count/sizeof统计数组中单元数目或对象中的属性个数

  for($i = 0; $i < count($users);$i++){
    echo $users[$i];
    echo &#39;<br/>&#39;;
  }
//还可以通过foreach循环来遍历数组,这种好处在于不需要考虑key
  foreach($users as $value){
    echo $value.&#39;<br/>&#39;;//点号为字符串连接符号
  }
//foreach循环遍历 $key => $value;$key和$value是变量名,可以自行设置
  foreach($users as $key => $value){
    echo $key.&#39;<br/>&#39;;//输出键
  }
?>
Copy after login

Create an array of custom keys

<?php

  //创建自定义键的数组
  $ceo = array(&#39;apple&#39;=>&#39;jobs&#39;,&#39;microsoft&#39;=>&#39;Nadella&#39;,&#39;Larry Page&#39;,&#39;Eric&#39;);
  //如果不去声明元素的key,它会从零开始
  print_r($ceo);//Array ( [apple] => jobs [microsoft] => Nadella [0] => Larry Page [1] => Eric )

  echo $ceo[&#39;apple&#39;];//jobs

   //php5.4起的用法
  $array = [
    "foo" => "bar",
    "bar" => "foo",
  ];

  print_r($array);//Array ( [foo] => bar [bar] => foo ) 

?>
Copy after login

From php5.4 onwards, you can use short array definition syntax and use [] instead of array(). It is somewhat similar to the definition of arrays in JavaScript.

Use of each()

<?php
  //通过为数组元素赋值来创建数组
  $ages[&#39;trigkit4&#39;] = 22;
  echo $ages.&#39;<br/>&#39;;//Array
  //因为相关数组的索引不是数字,所以无法通过for循环来进行遍历操作,只能通过foreach循环或list()和each()结构

  //each的使用
  //each返回数组中当前的键/值对并将数组指针向前移动一步
  $users = array(&#39;trigkit4&#39;=>22,&#39;mike&#39;=>20,&#39;john&#39;=>30);
  //print_r(each($users));//Array ( [1] => 22 [value] => 22 [0] => trigkit4 [key] => trigkit4 )

  //相当于:$a = array([0]=>trigkit4,[1]=>22,[value]=>22,[key]=>trigkit4);
  $a = each($users);//each把原来的数组的第一个元素拿出来包装成新数组后赋值给$a
  echo $a[0];//trigkit4

  //!!表示将真实存在的数据转换成布尔值
  echo !!each($users);//1

?>
Copy after login

The pointer of each points to the first key-value pair, and returns the first array element, obtains its key-value pair, and Packed into a new array

Usage of list() list is used to assign the values ​​​​of the array to some variables, see the following example:

<?php

  $a = [&#39;2&#39;,&#39;abc&#39;,&#39;def&#39;];
  list($var1,$var2) = $a;
  echo $var1.&#39;<br/>&#39;;//2
  echo $var2;//abc

  $a = [&#39;name&#39;=>&#39;trigkit4&#39;,&#39;age&#39;=>22,&#39;0&#39;=>&#39;boy&#39;];
  //list只认识key为数字的索引
  list($var1,$var2) = $a;

  echo $var1;//boy

?>
Copy after login

Note: only list is recognized The index where the key is a number

Sorting of array elementsReverse sorting: sort(), asort() and ksort() are all forward sorting, of course there is also a corresponding reverse sorting.
Implement reverse: rsort(), arsort() and krsort().

The array_unshift() function adds new elements to the head of the array, and the array_push() function adds each new element to the end of the array.
array_shift() deletes the first element at the head of the array. The opposite function is array_pop(), which deletes and returns an element at the end of the array.
array_rand() returns one or more keys in the array.

The function shuffle() randomly sorts the elements of the array.
Function array_reverse() gives a reverse sorting of the original array
Use of various APIs for arrayscount() and sizeof() count the number of array subscripts
array_count_values( ) Count the number of subscript values ​​in the array

<?php
  $numbers = array(&#39;100&#39;,&#39;2&#39;);
  sort($numbers,SORT_STRING);//按字符串排序,字符串只比较第一位大小
  print_r($numbers);//Array ( [0] => 100 [1] => 2 )

  $arr = array(&#39;trigkit4&#39;,&#39;banner&#39;,&#39;10&#39;);
  sort($arr,SORT_STRING);
  print_r($arr);//Array ( [0] => 10 [1] => banner [2] => trigkit4 )

  shuffle($arr);
  print_r($arr);//随机排序

  $array = array(&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;0&#39;,&#39;1&#39;);
  array_reverse($array);
  print_r($array);//原数组的反向排序。 Array ( [0] => a [1] => b [2] => c [3] => d [4] => 0 [5] => 1 )


  //数组的拷贝
  $arr1 = array( &#39;10&#39; , 2);
  $arr2 = &$arr1 ;
  $arr2 [] = 4 ; // $arr2 被改变了,$arr1仍然是array(&#39;10&#39;, 3)
  print_r($arr2);//Array ( [0] => 10 [1] => 2 [2] => 4 )

  //asort的使用
  $arr3 = & $arr1 ;//现在arr1和arr3是一样的
  $arr3 [] = &#39;3&#39; ;
  asort($arr3);//对数组进行排序并保留原始关系
  print_r($arr3);// Array ( [1] => 2 [2] => 3 [0] => 10 )

  //ksort的使用
  $fruits = array(&#39;c&#39;=>&#39;banana&#39;,&#39;a&#39;=>&#39;apple&#39;,&#39;d&#39;=>&#39;orange&#39;);
  ksort($fruits);
  print_r($fruits);//Array ( [a] => apple [c] => banana [d] => orange )

  //unshift的使用
  array_unshift($array,&#39;z&#39;);//开头处添加一元素
  print_r($array);//Array ( [0] => z [1] => a [2] => b [3] => c [4] => d [5] => 0 [6] => 1 ) 

  //current(pos)的使用
  echo current($array);//z;获取当前数组中的当前单元

  //next的使用
  echo next($array);//a;将数组中的内部指针向前移动一位

  //reset的使用
  echo reset($array);//z;将数组内部指针指向第一个单元

  //prev的使用
  echo next($array);//a;
  echo prev($array);//z;倒回一位

  //sizeof的使用
  echo sizeof($array);//7;统计数组元素的个数

  //array_count_values
  $num = array(10,20,30,10,20,1,0,10);//统计数组元素出现的次数
  print_r(array_count_values($num));//Array ( [10] => 3 [20] => 2 [30] => 1 [1] => 1 [0] => 1 ) 

?>
Copy after login

current(): Each array has an internal pointer pointing to its current unit, initially pointing to the first element inserted into the array

for loop traverses

<?php
  $value = range(0,120,10);
  for($i=0;$i<count($value);$i++){
    print_r($value[$i].&#39; &#39;);//0 10 20 30 40 50 60 70 80 90 100 110 120 
  }
?>
Copy after login

Instance of arrayUsage of array_pad function

<?php
  //array_pad函数,数组数组首尾选择性追加
  $num = array(1=>10,2=>20,3=>30);
  $num = array_pad($num,4,40);
  print_r($num);//Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 )

  $num = array_pad($num,-5,50);//array_pad(array,size,value)
  print_r($num);//Array ( [0] => 50 [1] => 10 [2] => 20 [3] => 30 [4] => 40 ) 
?>
Copy after login

size: the specified length. Integers are padded to the right, and negative numbers are padded to the left.

Use of unset()

 <?php
  //unset()的使用
  $num = array_fill(0,5,rand(1,10));//rand(min,max)
  print_r($num);//Array ( [0] => 8 [1] => 8 [2] => 8 [3] => 8 [4] => 8 ) 
  echo &#39;<br/>&#39;;

  unset($num[3]);
  print_r($num);//Array ( [0] => 8 [1] => 8 [2] => 8 [4] => 8 ) 
?>
Copy after login

Use of array_fill()

<?php
  //array_fill()的使用
  $num = range(&#39;a&#39;,&#39;e&#39;);
  $arrayFilled = array_fill(1,2,$num);//array_fill(start,number,value)
  echo &#39;<pre class="brush:php;toolbar:false">&#39;;

  print_r($arrayFilled);

?>
Copy after login

Use of array_combine()

<?PHP
  $number = array(1,2,3,4,5);
  $array = array("I","Am","A","PHP","er");
  $newArray = array_combine($number,$array);
  print_r($newArray);//Array ( [1] => I [2] => Am [3] => A [4] => PHP [5] => er ) 
?>
Copy after login

array_splice() deletes array members

<?php
  $color = array("red", "green", "blue", "yellow");
  count ($color); //得到4
  array_splice($color,1,1); //删除第二个元素
  print_r(count ($color)); //3
  echo $color[2]; //yellow
  echo $color[1]; //blue
?>
Copy after login

array_unique deletes duplicate values ​​in the array

<?php
  $color=array("red", "green", "blue", "yellow","blue","green");
  $result = array_unique($color);
  print_r($result);//Array ( [0] => red [1] => green [2] => blue [3] => yellow ) 
?>
Copy after login

array_flip() exchange The key and value of the array

<?PHP
  $array = array("red","blue","red","Black");
  print_r($array);
  echo "<br />";
  $array = array_flip($array);//
  print_r($array);//Array ( [red] => 2 [blue] => 1 [Black] => 3 ) 
?>
Copy after login

array_search() search value

<meta charset="utf-8">
<?php
  $array = array("red","blue","red","Black");
  $result=array_search("red",$array)//array_search(value,array,strict)
  if(($result === NULL)){
    echo "不存在数值red";
  }else{
    echo "存在数值 $result";//存在数值 0 
  }
?>
Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone Learning helps.

Related recommendations:

PHP introductory tutorial sharing of uploading file examples

##PHP half (half) search algorithm example analysis

PHP introductory tutorial sharing of uploading file examples

The above is the detailed content of Detailed explanation of commonly used array operation methods in PHP. 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 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

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

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

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