Home Backend Development PHP Tutorial Summary of usage of php array operations

Summary of usage of php array operations

Jun 28, 2017 am 11:43 AM

php defines arrays

1

2

3

4

<?php 

    $array = [];

    $array["key"] = "value";

 ?>

Copy after login

There are two main ways to declare arrays in PHP:

  1. Declare arrays using the array() function.

  2. 2. Directly assign values ​​to array elements.

1

2

3

4

5

6

7

8

9

<?php   

    //array数组

    $users = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;];

    echo $users;//只会打印出数据类型Arra

    print_r($users);//Array ( [0] => a[1] => b[2] => c[3] => d)

    $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更合适

Copy after login

//Display all the values ​​in the array through loops

1

2

3

4

for($i = 0 ;$i < 5;$i++){

      echo $users[$i];

      echo &#39;<br/>&#39;;

  }

Copy after login

//Use count/sizeof to count the number of units in the array or the number of attributes in the object

1

2

3

4

for($i = 0; $i < count($users);$i++){

       echo $users[$i];

       echo &#39;<br/>&#39;;

   }

Copy after login

//You can also traverse the array through a foreach loop. The advantage is that you don’t need to consider the key

1

2

3

4

5

6

7

8

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 with custom keys

Usage of

1

2

3

4

5

6

<?php

    // 创建自定义的数组

    $array = ["a"=>1,"b"=>2,"c"=>3,"d","e"];

    //如果没有声明键,它会从零开始

    print_r($array);//array([a]=>1,[b]=>2,[c]=>3,[0]=>d,[1]=>e);

?>

Copy after login

each()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?php   

      //通过为数组元素赋值来创建数组

      $array[&#39;key&#39;] = 22;

      echo $array.&#39;<br/>&#39;;//Array

      //因为相关数组的索引不是数字,所以无法通过for循环来进行遍历操作,只能通过foreach循环或list()和each()结构

      //each的使用

      //each返回数组中当前的键/值对并将数组指针向前移动一步

      $users = array(&#39;key&#39;=>22,&#39;key1&#39;=>20,&#39;key2&#39;=>30);

      //print_r(each($users));//Array ( [1] => 22 [value] => 22 [0] => array[key] => array)

      //相当于:$a = array([0]=>array,[1]=>22,[value]=>22,[key]=>array);

  $a = each($users);//each把原来的数组的第一个元素拿出来包装成新数组后赋值给$a

  echo $a[0];//array    //!!表示将真实存在的数据转换成布尔值

  echo !!each($users);//1

  ?>

Copy after login


## The pointer of each points to the first key-value pair and returns For the first array element, get its key-value pair and package it into a new array

Use of list()

list is used to use the array Assign values ​​to some variables, see the following example:

1

2

3

4

5

6

7

8

9

10

<?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: list only recognizes indexes whose keys are numbers

Sorting of array elements

## Reverse sorting: sort(), asort() and ksort() are all forward Sorting, of course, also has a corresponding reverse sorting.

Implementation of 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()删除数组头第一个元素,与其相反的函数是 array_pop(),删除并返回数组末 尾的一个元素。

array_rand()返回数组中的一个或多个键。

函数shuffle()将数组个元素进 行随机排序。

函数 array_reverse()给出一个原来数组的反向排序

数组的各类API的使用

注:count()和 sizeof()统计数组下标的个数
array_count_values()统计数组内下标值的个数

1

2

3

4

5

6

7

8

9

10

11

12

13

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

 ?>

Copy after login

//数组的拷贝

1

2

3

4

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

Copy after login

//asort的使用

1

2

3

4

$arr3  = & $arr1 ;//现在arr1和arr3是一样的

 $arr3 [] =  &#39;3&#39; ;

 asort($arr3);//对数组进行排序并保留原始关系

 print_r($arr3);// Array ( [1] => 2 [2] => 3 [0] => 10 )

Copy after login

//ksort的使用

1

2

3

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

Copy after login

//unshift的使用

1

2

  array_unshift($array,&#39;z&#39;);//开头处添加一元素

print_r($array);//Array ( [0] => z [1] => a [2] => b [3] => c [4] => d [5] => 0 [6] => 1 )

Copy after login

//current(pos)的使用

1

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

Copy after login


//next的使用

1

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

Copy after login


//reset的使用

1

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

Copy after login


//prev的使用

1

2

echo next($array);//a;

 echo prev($array);//z;倒回一位

Copy after login

1

2

3

4

5

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

urrent():每个数组都有一个内部指针指向他的当前单元,初始指向插入到数组中的第一个元素

for循环遍历

1

2

3

4

5

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


数组的实例

array_pad函数的使用

1

2

3

4

5

6

7

8

<?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:指定的长度。整数则填补到右侧,负数则填补到左侧。

unset()的使用

1

2

3

4

5

6

7

8

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

array_fill()的使用

1

2

3

4

5

6

7

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

array_combine()的使用

1

2

3

4

5

6

<?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()删除数组成员

1

2

3

4

5

6

7

<?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删除数组中的重复值

1

2

3

4

<?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()交换数组的键值和值

1

2

3

4

5

6

<?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()搜索数值

1

2

3

4

5

6

7

8

9

10

<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



The above is the detailed content of Summary of usage of php array operations. 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

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)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

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,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles