search
HomeBackend DevelopmentPHP TutorialPHP introductory tutorial summary of array usage (create, delete, traverse, sort, etc.)

The examples in this article summarize the usage of PHP arrays. Share it with everyone for your reference, the details are as follows:

Demo1.php

<?php
  //创建一个数组变量
  $userNames = array(&#39;张三&#39;,&#39;李四&#39;,&#39;王五&#39;);
  //将这个数组打印出来
// echo $userNames;//Array
// $userName = &#39;张三&#39;;
// echo $userName;//张三
  //如果你想打印出这个数组的某一个元素
  //那你必须找到这个元素的下标,键(key)
  //0,1,2
  //echo $userNames[2];//王五
  //print_r -- 打印关于变量的易于理解的信息。
  //print_r($userNames);//Array ( [0] => 张三 [1] => 李四 [2] => 王五 )
  //$userNames 是一个数组变量,而 $userNames[x] 可以理解成数组变量下的小变量
  $userNames[4] = &#39;赵七&#39;;
  print_r($userNames);//Array ( [0] => 张三 [1] => 李四 [2] => 王五 [4] => 赵七 )
?>

Demo2.php

<?php
  //range -- 建立一个包含指定范围单元的数组
  //range 包含指定数组
  //包含两种东西,一种叫做键(key),一种叫做值(value)
  //key 是自动生成的,默认从 0 开始,每次 +1
  //value 是你自己赋值的
  //$numbers = range(1,4);
  //print_r($numbers);  //Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
// $letters = range(&#39;a&#39;,&#39;e&#39;);
// print_r($letters);//Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )
// echo $letters[3];
?>

Demo3.php

<?php
  $userNames = array(&#39;张三&#39;,&#39;李四&#39;,&#39;王五&#39;);
  //通过循环来显示数组里的所有值
  //从 0-5 之间循环
// for($i=0;$i<3;$i++){
//   echo ($i+1).&#39;-->&#39;.$userNames[$i].&#39;<br/>&#39;;
// }
  /*
   * 1-->张三
   * 2-->李四
   * 3-->王五
   * */
// echo count($userNames); //3
// for($i=0;$i<count($userNames);$i++){
//   echo ($i+1).&#39;-->&#39;.$userNames[$i].&#39;<br/>&#39;;
// }
  //如果 key 不是从 0 开始,或者说,压根不是数字,那么就无法用无精打采循环来实现显示数据列表
  //通过 foreach 循环来遍历数组,这方式好处,不需要去考虑 key
// foreach ($userNames as $value){
//   echo $value.&#39;<br/>&#39;;
// }
  //foreach 遍历 $key => $value
// foreach ($userNames as $keyaaa => $value){
//   echo $keyaaa.&#39;-->&#39;.$value.&#39;<br/>&#39;;
// }
  /**
   * 0-->张三
   * 1-->李四
   * 2-->王五
   * */
  //所以,你要先做个判断
  if(is_array($userNames)){
    foreach ($userNames as $key => $value){
      echo $key.&#39;-->&#39;.$value.&#39;<br/>&#39;;
    }
  }else{
    echo $userNames;
  }
?>

Demo4.php

<?php
  $userNames = array(&#39;张三&#39;,&#39;李四&#39;,&#39;王五&#39;);
  print_r($userNames);
  echo $userNames[0];
?>

Demo5.php

<?php
  //创建自定义键(key)的数组
  //如果你不去声明元素的 key ,那么从开始 0 计算
// $userNames = array(&#39;baidu&#39;=>&#39;张三&#39;,&#39;李四&#39;,&#39;王五&#39;);
// print_r($userNames); //Array ( [baidu] => 张三 [0] => 李四 [1] => 王五 )
  $userNames = array(&#39;baidu&#39;=>&#39;张三&#39;,&#39;taobao&#39;=>&#39;李四&#39;,&#39;360&#39;=>&#39;王五&#39;);
  print_r($userNames); //Array ( [baidu] => 张三 [taobao] => 李四 [360] => 王五 )
  echo $userNames[&#39;baidu&#39;];
?>

Demo6.php

<?php
  //先创建只一个元素的数组
  $userAge = array(&#39;chaoyv&#39;=>25);
  //打印出 chaoyv 的年龄
  //echo $userAge[&#39;chaoyv&#39;]; //25
  //将以前的数组,追加两条,这里说的下标,键,key 是一个东西
  $userAge[&#39;yike&#39;] = 30;
  $userAge[&#39;wife&#39;] = 24;
  print_r($userAge);
?>

Demo7.php

<?php
  //array 关键字都可以不要,就能创建数组
  $userAges[&#39;chaoyv&#39;] = 25;
  //print_r($userAges); //Array ( [chaoyv] => 25 )
  $userAges[&#39;yike&#39;] = 30;
  $userAges[&#39;wife&#39;] = 24;
  //print_r($userAges); //Array ( [chaoyv] => 25 [yike] => 30 [wife] => 24 )
  //这里无法使用 for 循环将数据全部显示出来,只能通过 foreach 遍历出来
  foreach ($userAges as $value){
    echo $value.&#39;<br/>&#39;;
  }
?>

Demo8.php

<?php
// $userAges[&#39;chaoyv&#39;] = 25;
// $userAges[&#39;yike&#39;] = 30;
// $userAges[&#39;wife&#39;] = 24;
  $username = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  //print_r($username);
  //each 的使用
  //each -- 返回数组中当前的键/值对并将数组指针向前移动一步
  //这里有一个指针,默认情况下,指针是指定第一个键值对
  //这里的第一个键值对是 &#39;世&#39;=>&#39;何开&#39;
  //如果each($username),那么获取的就是第一个键值对 &#39;世&#39;=>&#39;何开&#39;
  //each 这个函数返回的是一个数组,
  //each 将第一个键值对获取到,然后包装成一个新的数组。
  //print_r(each($username));
  //相当于 $a = Array ( [1] => 何开 [value] => 何开 [0] => 世 [key] => 世 )
  //$a = each($username);
  //echo $a[value];
  print_r(each($username));
  echo &#39;<br/>&#39;;
  print_r(each($username));
?>

Demo9.php

<?php
  $username = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  //这里,我们怎么使用 each 来循环所有的数据呢?
  //相当于 $a = Array ( [1] => 何开 [value] => 何开 [0] => 世 [key] => 世 )
  //两个感叹号,表示真是存在的数据转换成布尔值
// echo !!each($username);//说明有数据,有数据,用布尔值的理念就是真(true)
// echo !!each($username);
// echo !!each($username);
// echo !!each($username);//第四个是假的
  while (!!$a = each($username)){
    echo $a[&#39;key&#39;].&#39;-->&#39;.$a[&#39;value&#39;].&#39;<br/>&#39;;
  }
// $a = each($username);
// echo $a[0].&#39;---&#39;.$a[1].&#39;<br/>&#39;;
// $a = each($username);
// echo $a[0].&#39;---&#39;.$a[1].&#39;<br/>&#39;;
// $a = each($username);
// echo $a[0].&#39;---&#39;.$a[1].&#39;<br/>&#39;;
// /**
//  * 世---何开
//  * 血---赵血儿
//  * 学---墨学之
//  * */
?>

Demo10.php

<?php
// $usernames = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
// $a = each($usernames);
// //世-->何开
// echo $a[&#39;key&#39;];
// echo &#39;-->&#39;;
// echo $a[&#39;value&#39;];
// $a = each($usernames);
// //血-->赵血儿
// echo $a[&#39;key&#39;];
// echo &#39;-->&#39;;
// echo $a[&#39;value&#39;];
// //list -- 把数组中的值赋给一些变量
// $a = array(&#39;aaa&#39;,&#39;bbb&#39;,&#39;ccc&#39;,&#39;ddd&#39;);
////  print_r($a);//Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd )
// list($var1,$var2,$var3,$var4) = $a;
// echo $var4;
// $usernames = array(0=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
// //list 只能认识 key 为数字的
// //自定义的字符串 key 是无法使用 list 来识别的
// list($a,$b,$c) = $usernames;
// echo $a;//何开
  $usernames = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  //相当于 $a = Array ( [1] => 何开 [value] => 何开 [0] => 世 [key] => 世 )
  list($name,$username) = each($usernames);
  echo $username;
?>

Demo11.php

<?php
  $usernames = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  $a =each($usernames);
  echo $a[key];
  $a =each($usernames);
  echo $a[key];
  //第三次,我想取数组的第一条数组
  //只要将数组的指针调整到第一个位置即可
  //reset -- 将数组的内部指针指向第一个单元
  reset($usernames);
  $a = each($usernames);
  echo $a[key];
  //世血世
?>

Demo12.php

<?php
// $usernames = array(&#39;世&#39;=>&#39;何开&#39;,&#39;境&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
// print_r($usernames);
// echo &#39;<br/>&#39;;
// //array_unique -- 移除数组中重复的值
// //创建了一个新数组,而新数组呢,已经移除掉了,旧的数组原封不动
// $a = array_unique($usernames);
// print_r($a);
  $numbers = array(1,24,2,1,3,4,2,6,4,2,4,56,2,4,5);
  print_r($numbers);
  $newNumbers = array_unique($numbers);
  print_r($newNumbers);
?>

Demo13.php

<?php
  $usernames = array(&#39;世&#39;=>&#39;何开&#39;,&#39;境&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  print_r($usernames);
  echo &#39;<br/>&#39;;
  //array_flip -- 交换数组中的键和值
  $newUsernames = array_flip($usernames);
  print_r($newUsernames);
  /**
   * Array ( [世] => 何开 [境] => 何开 [血] => 赵血儿 [学] => 墨学之 )
   * Array ( [何开] => 境 [赵血儿] => 血 [墨学之] => 学 )
   * */
?>

Demo14.php

<?php
  //创建一个单一的数组
  $products = array(
    array(&#39;苹果&#39;,&#39;6&#39;,&#39;28.8&#39;),
    array(&#39;猪肉&#39;,&#39;2&#39;,&#39;18.8&#39;),
    array(&#39;饼干&#39;,&#39;4&#39;,&#39;48.8&#39;)
  );
  //print_r($products);
  //将 $products 第一条元素取出来
  //print_r($products[2]);
  //数组里的数组
  echo "|".$products[0][0]."|".$products[0][1]."|".$products[0][2]."|<br />";
  echo "|".$products[1][0]."|".$products[1][1]."|".$products[1][2]."|<br />";
  echo "|".$products[2][0]."|".$products[2][1]."|".$products[2][2]."|<br />";
?>

Demo15.php

<?php
  //创建一个单一的数组
  $products = array(
    array(&#39;苹果&#39;,&#39;6&#39;,&#39;28.8&#39;),
    array(&#39;猪肉&#39;,&#39;2&#39;,&#39;18.8&#39;),
    array(&#39;饼干&#39;,&#39;4&#39;,&#39;48.8&#39;)
  );
  //首先要求出外面数组的长度
  //echo count($products);
  for($i=0; $i<count($products);$i++){
    for($j=0;$j<count($products[$i]);$j++){
      echo &#39;|&#39;.$products[$i][$j];
    }
    echo "|<br/>";
  }
  /*
   * |苹果|6|28.8|
   * |猪肉|2|18.8|
   * |饼干|4|48.8|
   * **/
?>

Demo16.php

<?php
  //创建一个单一的数组
  $products = array(
    array(&#39;产品&#39;=>&#39;苹果&#39;,&#39;数量&#39;=>&#39;6&#39;,&#39;价格&#39;=>&#39;28.8&#39;),
    array(&#39;产品&#39;=>&#39;猪肉&#39;,&#39;数量&#39;=>&#39;3&#39;,&#39;价格&#39;=>&#39;25.8&#39;),
    array(&#39;产品&#39;=>&#39;饼干&#39;,&#39;数量&#39;=>&#39;2&#39;,&#39;价格&#39;=>&#39;26.8&#39;)
  );
  //print_r($products)  ;
// for($i=0;$i<count($products);$i++){
//   foreach ($products[$i] as $key => $value){
//     echo $key.&#39;--&#39;.$value.&#39;|&#39;;
//   }
//   echo &#39;<br/>&#39;;
// }
  for($i=0;$i<count($products);$i++){
    while (!!list($key,$value)=each($products[$i])){
      echo $key.&#39;--&#39;.$value.&#39;|&#39;;
    }
    echo &#39;<br/>&#39;;
  }
  /**
   * 产品--苹果|数量--6|价格--28.8|
   * 产品--猪肉|数量--3|价格--25.8|
   * 产品--饼干|数量--2|价格--26.8|
   * */
?>

Demo17.php

<?php
// //sort -- 对数组排序
// $fruit = array(&#39;banner&#39;,&#39;orange&#39;,&#39;apple&#39;);
// //没有排序前,一般是按照 key 的顺序进行显示
// //print_r($fruit);
// //排序之后
// sort($fruit);
// print_r($fruit);
  $numbers = array(45,44,27,574,241,7,45,1,5,2,4,5);
  print_r($numbers);
  rsort($numbers);
  echo &#39;<br/>&#39;;
  print_r($numbers);
  //按照数字的话,要看整体的数字的大小,按照字符串的话,只看第一位大小
// $numbers = array(2,12,3);
// sort($numbers,SORT_NUMERIC);
// print_r($numbers);Array ( [0] => 2 [1] => 3 [2] => 12 )
// $numbers = array(2,12,3);
// sort($numbers,SORT_STRING);
// print_r($numbers);//Array ( [0] => 12 [1] => 2 [2] => 3 )
?>

Demo18.php

<?php
//asort -- 对数组进行排序并保持索引关系
  $fruit = array(&#39;banner&#39;,&#39;orange&#39;,&#39;apple&#39;);
// sort($fruit);
// print_r($fruit);
  //Array ( [0] => apple [1] => banner [2] => orange )
  asort($fruit);
  print_r($fruit);
  //Array ( [2] => apple [0] => banner [1] => orange )
?>

Demo19.php

<?php
  $fruit = array(&#39;b&#39;=>&#39;banner&#39;,&#39;o&#39;=>&#39;orange&#39;,&#39;a&#39;=>&#39;apple&#39;);
  //ksort -- 对数组按照键名排序
  ksort($fruit)  ;
  print_r($fruit);
  //Array ( [a] => apple [b] => banner [o] => orange )
?>

Demo20.php

<?php
  //echo &#39;<img  src="/static/imghwm/default1.png"  data-src="images/mm1.jpg"  class="lazy"   / alt="PHP introductory tutorial summary of array usage (create, delete, traverse, sort, etc.)" >&#39;;
  //创建一个数组
  $pic = array(&#39;mm1.jpg&#39;,&#39;mm2.jpg&#39;,&#39;mm3.jpg&#39;,&#39;mm4.jpg&#39;,&#39;mm5.jpg&#39;);
  //数组进行随机打乱
  //shuffle($pic);
  //多数组进行反向排序,array 打头的函数,一般会创建一个新数组
  $a = array_reverse($pic);
  for($i=0;$i<3;$i++){
    echo &#39;<img  src="/static/imghwm/default1.png"  data-src="images/&#39;.$a[$i].&#39;"  class="lazy"     style="max-width:90%" / alt="PHP introductory tutorial summary of array usage (create, delete, traverse, sort, etc.)" >&#39;;
    echo "\n";
  }
?>

Demo21.php

<?php
  $userName = array(&#39;张三&#39;);
  print_r($userName);
  //这个函数的返回值将得到 ,目前数组的元素个数
  //array_unshift -- 在数组开头插入一个或多个单元
  //在开头插入数据
  array_unshift($userName,&#39;李四&#39;)  ;
  //在结尾插入数据
  array_push($userName,&#39;吴者然&#39;);
  //删除开头的元素
  array_shift($userName);
  //删除结尾的元素
  array_pop($userName);
  print_r($userName);
?>

Demo22.php

<?php
  $fruit = array(&#39;banner&#39;,&#39;orange&#39;,&#39;apple&#39;);
  //这个函数用来获取一个数组中的键(key)
  //第二个参数表明随即获取几个
// $a = array_rand($fruit,1);
// echo $fruit[$a];
  $a = array_rand($fruit,2);
  echo $fruit[$a[0]].&#39; &#39;.$fruit[$a[1]];
?>

Demo23.php

<?php
  $username = array(&#39;世&#39;=>&#39;何开&#39;,&#39;血&#39;=>&#39;赵血儿&#39;,&#39;学&#39;=>&#39;墨学之&#39;);
  //默认情况下,指针在第一条数据
  //获取指针的当前元素,current 并没有将指针移到下一步
// echo current($username);
// echo current($username);
// echo current($username);
// echo next($username);
// echo current($username);
// echo next($username);
// echo current($username);
// //reset -- 将数组的内部指针指向第一个单元
// echo reset($username);
// echo sizeof($username);//count
  $numbers = array(1,4,5,656,7,5,7,4,7,4,5,7);
  //array_count_values -- 统计数组中所有的值出现的次数
  print_r(array_count_values($numbers));
?>

Demo24.php

<?php
  $a=$b=$c=&#39;&#39;;
  $fruits = array(&#39;a&#39;=>&#39;apple&#39;,&#39;b&#39;=>&#39;banner&#39;,&#39;c&#39;=>&#39;orange&#39;);
  //通过标量函数将字符串键(key)设置成变量,然后将值赋给了这个变量
  extract($fruits);
  echo $a;
  echo $c;
  echo $b;
  //appleorangebanner
?>

I hope this article will be helpful to everyone in PHP programming.

For more PHP introductory tutorials on array usage summary (creation, deletion, traversal, sorting, etc.), please pay attention to 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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

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