数组是特殊的变量,他可以同时保存一个以上的值

在PHP 中创建数组

在PHP 中,array() 函数用于创建数组:
在PHP 中,有三种数组类型:

  • 索引数组 带有数字索引的数组
  • 关联数组 带有指定键的数组
  • 多维数组 包含一个或多个数组的数组

    PHP 索引数组

    有两种创建索引数组的方法:
    索引是自动分配的(索引从 0 开始)

    1. $info = array("lili", 18, "女");
    1. $info[0] = "lili";
    2. $info[1] = 18;
    3. $info[2] = "女";
    1. <?php
    2. $info = array("lili", 18, "女");
    3. echo "name is $info[0], age is $info[1], sex is $info[2]";
    4. ?>

    获的数组的长度 count() 函数

    count() 函数用于返回数组的长度(元素数)

    <?php
     $info = array("lili", 18, "女");
     echo count($info);
    ?>
    

    遍历索引数组

    如需遍历并输出索引数组的所有值,可以使用for 循环

    <?php
    $info = array("lili", 18, "女");
    $arrLength = count($info);
    for ($x=0; $x<$arrLength; $x++) {
       echo "$info[$x]\n";
    }
    ?>
    

    PHP 关联数组

    关联数组是使用你分配给数组的指定键的数组。

    $age = array("bob"=>12, "lili"=>14, "hehe"=>16);
    
    $age["bob"] = 12;
    $age["lili"] = 14;
    $age["hehe"] = 16;
    
    <?php 
    $age = array("bob"=>12, "lili"=>14, "hehe"=>16);
    
    echo $age['bob'];
    ?>
    

    遍历关联数组

    如果需要遍历并输出关联数组的所有值,可以使用 foreach 循环

    <?php
    $age = array("bob"=>12, "lili"=>14, "hehe"=>16);
    
    foreach ($age as $x=>$x_value){
      echo "$x => $x_value\n";
    }
    ?>
    

    PHP 数组排序

    数组中的元素能够以字母或数字顺序进行升序或降序排序

    PHP 数组的排序函数

  • sort() 以升序对数组排序

  • rsort() 以降序对数组排序
  • asort() 根据值,以升序对关联数组进行排序
  • ksort() 根据键,以升序对关联数组进行排序
  • arsort() 根据值,以降序对关联数组进行排序
  • krsort() 根据键,以降序对关联数组进行排序

    对数组进行升序排序 sort()

    <?php
    $info = array("lili", "bobo", "haha");
    sort($info);
    echo $info[0],"\n", $info[1],"\n", $info[2];
    ?>
    

    根据值对数组进行升序排序 asort()

    <?php
    $age = array("bob"=>12, "lili"=>14, "hehe"=>16);
    asort($age);
    ?>