1.使用数组实现堆栈 //后进后出
array_push() array_pop()
//使用数组实现堆栈
$b=array(1,2,3,4);
$b[]="a";//入栈
array_push($b,"b","c");//使用函数入栈,从最后的位置插入
print_r($b);//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => a [5] => b [6] => c )
$value=array_pop($b);//使用函数出栈
print_r($b);//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => a [5] => b )
echo $value;//显示出栈的元素的值 c
2.使用数组实现队列 //先进先出
array_unshift() array_shift()
//使用数组实现队列
$c=array(1,2,3);
print_r($c);//Array ( [0] => 1 [1] => 2 [2] => 3 );
array_unshift($c,"abc","bcd");//入队,从开始的位置插入
print_r($c);//Array ( [0] => abc [1] => bcd [2] => 1 [3] => 2 [4] => 3 )
$values=array_shift($c);//出队
print_r($c);// Array ( [0] => bcd [1] => 1 [2] => 2 [3] => 3 )
unset($c[2]);//删除指定位置元素
print_r($c);//Array ( [0] => bcd [1] => 1 [3] => 3 )
//array_rand() 随机返回数组下标
$arr=array(1,3,4,5,76,7,99,6,2,3);
echo array_rand($arr);//返回的是随机的数组元素的下标
echo $arr[array_rand($arr)];//随机显示数组元素的值
//shuffle() 随机重新排列数组
$arr2=array(32,35,33);
shuffle($arr2);
print_r($arr2);//数组元素位置随机变换
//array_sum() 求和
$arr3=array(1,3,5);
echo array_sum($arr3); //返回9
print_r($arr3);//Array ( [0] => 1 [1] => 3 [2] => 5 )
//range(最小值,最大值,步长)
$arr4=range(0,100,10);
print_r($arr4);//Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 [6] => 60 [7] => 70 [8] => 80 [9] => 90 [10] => 100 )
已有 0 条评论