php学习7——数组
创建数组
$my_arr=array();
$my_arr=array('a','b','c','d');
$my_arr=array(1,2,3,4);
$my_arr=array('a'=>'x1','b'=>'x2','c'=>'x3','d'=>'x4');
$str=range('a','z');
print_r ($str);
out:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => i [9] => j [10] => k [11] => l [12] => m [13] => n [14] => o [15] => p [16] => q [17] => r [18] => s [19] => t [20] => u [21] => v [22] => w [23] => x [24] => y [25] => z )
$str=range('a','z');
print_r ($str);
out:Array ( [0] => a [1] => c [2] => e [3] => g [4] => i [5] => k [6] => m [7] => o [8] => q [9] => s [10] => u [11] => w [12] => y )
$str=range(0,10 ,-2);
print_r ($str);
out:Array ( [0] => 0 [1] => 2 [2] => 4 [3] => 6 [4] => 8 [5] => 10 )
访问数组
$my_arr[0];
$my_arr['a'];
输出数组
print_r(array,true)
var_export(array,true)
var_dump(array)
数组输出为字符串(两个函数是相同的互为别名)
implode(', ',array);
join(', ',array);
ex
$my_arr=array('a','b','c','d');
$str=implode('-',$my_arr);
echo $str;
out:a-b-c-d
$my_arr=array('a'=>'x1','b'=>'x2','c'=>'x3','d'=>'x4');
$str=implode('-',$my_arr);
echo $str;
out:x1-x2-x3-x4
只输出值或键
array_values(array)//把数组中的值输出为字符串
array_keys(array)//把数组中的键输出为字符串
数组追加
array_merge($arr,$arr2,……)
$my_arr1=array('a','b','c','d');
$my_arr2=array(1,2,3,4);
$my_arr3=array('a'=>'x1','b'=>'x2','c'=>'x3','d'=>'x4');
$new_arr=array_merge($my_arr1,$my_arr2);
$new_arr2=array_merge($my_arr1,$my_arr2,$my_arr3);
print_r( $new_arr) ;
print_r($new_arr2);
out:Array ( [0] => a [1] => b [2] => c [3] => d [4] => 1 [5] => 2 [6] => 3 [7] => 4 )
Array ( [0] => a [1] => b [2] => c [3] => d [4] => 1 [5] => 2 [6] => 3 [7] => 4 [a] => x1 [b] => x2 [c] => x3 [d] => x4 )
数组元素统计
count()=sizeof();
删除数组指定的元素,第一个元素和最后一个元素(栈和队列)
unset($array['key'])
array_shift(array)
array_pop(array)
删除一个或多个数组元素
array_splice(array,start,length)
array_slice(array,start,length)
查找
in_array($str,array) 返回bool值,存在返回true,否则返回false
array_key_exists($key,array)
数组处理
max(array),
min(array),
array_sum(array)
回调函数
array_walk(array,funcname)//会修改原数组
array_map(funcname,array)//不会修改原数组
array_filter(array,funcname)//