PHP数组_5_3_数组处理函数及其应用_1_快速创建数组的函数

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

 

一、快速创建数组的函数

PHP数组_5_3_数组处理函数及其应用_1_快速创建数组的函数

1. range() 函数

程序:

 1 <?php
 2 $numbers = range(1,5);
 3 print_r($numbers);
 4 echo "<br/>";
 5 $chars1 = range('a','d');
 6 print_r($chars1);
 7 echo "<br/>";
 8 $chars2 = range('d','a');
 9 print_r($chars2);
10 echo "<br/>";
11 ?>

输出:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
Array ( [0] => a [1] => b [2] => c [3] => d ) 
Array ( [0] => d [1] => c [2] => b [3] => a ) 

 

2. explode() 函数

程序:

1 <?php
2 $ip = "127.0.0.1";
3 $exploded = explode(".",$ip);
4 print_r($exploded);
5 echo "<br/>";
6 ?>

输出:

Array ( [0] => 127 [1] => 0 [2] => 0 [3] => 1 ) 

 

3. array_combine() 函数

程序:

1 <?php
2 $fruits = array( "apple", "banana", "orange" );
3 $colors = array( "red", "yellow", "orange" );
4 $temp = array_combine($fruits, $colors);    //$firuts的值做 $temp的键, $olors的值做 $temp的值
5 print_r($temp);
6 ?>

输出:

Array ( [apple] => red [banana] => yellow [orange] => orange )

 

4. array_fill()函数

程序:

1 <?php
2 $banana = array_fill(5, 3, 'banana');
3 print_r($banana);
4 echo "<br/>";
5 $orange = array_fill(5,-1, 'orange');   //length<0会提示 Warning警告信息
6 print_r($orange);
7 echo "<br/>";
8 ?>

输出:

PHP数组_5_3_数组处理函数及其应用_1_快速创建数组的函数

5. array_pad() 函数

程序:

 1 <?php
 2 $info = array('coffee','brown','caffeine');
 3 $tea1 = array_pad($info, 5, 'tea');
 4 $tea2 = array_pad($info, -7, 'tea');
 5 $tea3 = array_pad($info, 2, 'tea');
 6 print_r($tea1);
 7 echo "<br/>";
 8 print_r($tea2);
 9 echo "<br/>";
10 print_r($tea3);
11 ?>

输出:

Array ( [0] => coffee [1] => brown [2] => caffeine [3] => tea [4] => tea ) 
Array ( [0] => tea [1] => tea [2] => tea [3] => tea [4] => coffee [5] => brown [6] => caffeine ) 
Array ( [0] => coffee [1] => brown [2] => caffeine )

 

上一篇:C语言教师工资管理课设 求助


下一篇:&&前端&&找出字符串中最长的单词