PHP数组_5_3_数组处理函数及其应用_4_数组和变量间的转换函数

以下为学习孔祥盛主编的《PHP编程基础与实例教程》(第二版)所做的笔记。

 

数组和变量间的转换函数

PHP数组_5_3_数组处理函数及其应用_4_数组和变量间的转换函数

1. list() 语言结构

程序:

1 <?php
2 $info = array('coffee','brown','caffeine');
3 list($drink,$color,$power) = $info;
4 echo "$drink is $color and $power makes it special.<br/>";  //coffee is brown and caffeine makes it special.
5 list($drink,,$power) = $info;
6 echo "$drink has $power.<br/>";     //coffee has caffeine.
7 echo "I need $power.";      //I need caffeine.
8 ?>

输出:

coffee is brown and caffeine makes it special.
coffee has caffeine.
I need caffeine.

 

2. extract() 函数

程序:

 

 1 <?php
 2 $info = array("studentNo"=>"2010001","studentName"=>"张三","studentSex"=>"男");
 3 extract($info);
 4 echo $studentNo;
 5 echo "<br/>";
 6 echo $studentName;
 7 echo "<br/>";
 8 echo $studentSex;
 9 echo "<br/>";
10 ?>

输出:

2010001
张三
男

 

3. compact() 函数

程序:

1 <?php
2 $tel = "135***00000";
3 $email = "hello@qq.com";
4 $postCode = "453700";
5 $result = compact("tel","email","postCode");
6 print_r($result);   
7 ?>

输出:

Array ( [tel] => 135***00000 [email] => hello@qq.com [postCode] => 453700 )

 

数组的遍历

使用list()结构、each()函数和循环语句可以实现数组的遍历。

程序:

1 <?php
2 $colors = array('orange','red','yellow');
3 $fruits = array('orange','apple','banana');
4 $temp = array_combine($colors,$fruits);
5 reset($temp);
6 while(list($key,$value)=each($temp)){
7     echo $key."==>".$value."<br/>";
8 }
9 ?>

输出:

PHP数组_5_3_数组处理函数及其应用_4_数组和变量间的转换函数

 

说明:

  PHP 7.2 废弃了each()方法。

 

上一篇:【操作系统】银行家算法的例题详解


下一篇:node.js安装中途遇到的问题