search
HomeBackend DevelopmentPHP TutorialNotes on commonly used array operation methods in PHP, array operation methods_PHP tutorial

Collection of notes on commonly used array operation methods in PHP, overview of array operation methods


To access the contents of a variable, 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 on arrays
PHP defines array:

<&#63;php 
  $array = array(); 
  $array["key"] = "values"; 
&#63;> 

There are two main ways to declare arrays in PHP:

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

<&#63;php
  //array数组
  $users = array('phone','computer','dos','linux');
  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 '<br/>';
  }

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

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

Create an array of custom keys

<&#63;php

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

  echo $ceo['apple'];//jobs

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

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

&#63;>  

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

Usage of each()

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

  //each的使用
  //each返回数组中当前的键/值对并将数组指针向前移动一步
  $users = array('trigkit4'=>22,'mike'=>20,'john'=>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

&#63;> 

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

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

<&#63;php

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

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

  echo $var1;//boy

&#63;>

Note: list only recognizes indexes whose keys are numbers

Sort of array elements
Reverse sorting: sort(), asort() and ksort() are all forward sorting, and of course there is 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 an array.

The function shuffle() randomly sorts the elements of the array.
The function array_reverse() gives a reverse sort of the original array
Uses of various APIs for arrays
count() and sizeof() count the number of array subscripts
array_count_values() counts the number of subscript values ​​in the array

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

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

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

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


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

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

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

  //unshift的使用
  array_unshift($array,'z');//开头处添加一元素
  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 ) 

&#63;>  

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

for loop traversal

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

Instance of array
Usage of array_pad function

<&#63;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 ) 
&#63;>

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

Usage of unset()

 <&#63;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 '<br/>';

  unset($num[3]);
  print_r($num);//Array ( [0] => 8 [1] => 8 [2] => 8 [4] => 8 ) 
&#63;>

Usage of array_fill()

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

  print_r($arrayFilled);

&#63;>

Usage of array_combine()

<&#63;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 ) 
&#63;> 

array_splice() deletes array members

<&#63;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
&#63;> 

array_unique removes duplicate values ​​in an array

<&#63;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 ) 
&#63;> 

array_flip() exchanges the key and value of the array

<&#63;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 ) 
&#63;> 

array_search() search value

<meta charset="utf-8">
<&#63;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 
  }
&#63;> 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1127879.htmlTechArticleCommon array operation methods in PHP are organized and summarized. To access the content of a variable, you can use it directly. its name. If the variable is an array, you can use...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use