php基础知识(四)数组

<?php
  header("content-type:text/html;charset=gbk");
  printf("<h1>php数组</h1>");
  
  $ary =array("12",'3d','fs3');
  //Array
  echo $ary.'<br>';
  
  //格式化后输出 Array ( [0] => 12 [1] => 3d [2] => fs3 )
  print_r($ary);
  printf($ary.'<br>');
  print_r($ary[1]."<br>") ;
  
  //数组有相同元素,覆盖
  $a1 = array("1"=>"PHP","1"=>"Perl","2"=>"JAVA","6"=>"Ruby");
  
  print_r($a1);
  array_push($a1,"Ruby");
  print_r($a1);//Array ( [1] => Perl [2] => JAVA [6] => Ruby [7] => Ruby )
  print_r(array_unique($a1));//Array ( [1] => Perl [2] => JAVA [6] => Ruby )
  
  /**
   * 关联数组
   */
  $glAry =array("o"=>1,"t"=>2,"tr"=>'44r');
  
  print_r($glAry);
  echo $glAry["o"];
  //向数组中添加元素
  $glAry["s"]="ds";
  print_r($glAry);
  
  echo '数组元素的个数:'.count($glAry)."<br>";
  //搜索元素,找到返回索引值
  echo array_search("1", $glAry).'<br>';//o
  //取数组中最后一个元素
  echo   array_pop($glAry).'<br>';//ds
  //数组末尾添加元素,返回元素的索引
  echo array_push($glAry,'refre').'<br>';//4
  print_r($glAry);//Array ( [o] => 1 [t] => 2 [tr] => 44r [0] => refre ) 
  
  echo '<h2>二维数组</h2><br>';
  /**
   * 二维数组的定义
   */
  $tAry = array(array("3","43","f4"),array("32","f3",'php'));
  print_r($tAry);
  echo '<br>';
  foreach ($tAry as $i){
  	 foreach ($i as $j){
  	 	echo $j;
  	 }
  	 echo "<br>";
  }
  
  echo '数组元素的总个数:'.count($tAry,COUNT_NORMAL).'<BR>';//2
  echo '数组元素的总个数:'.count($tAry,COUNT_RECURSIVE).'<BR>';//8
  
  /**
   * 将字符串转化为数组
   * explode();
   */
   $str ="i , love ,you";
   //Array ( [0] => i , love ,you )
   print_r(explode(".", $str));
   
   //Array ( [0] => i [1] => love ,you ) 
   print_r(explode(",", $str,2));
   
  // Array ( [0] => i [1] => love [2] => you )
   print_r(explode(",", $str));
  /**
   * 将数组转化为字符串
   */ 
   $strT = implode(",", $a1);
   echo $strT;


你可能感兴趣的:(php基础知识(四)数组)