PHP 學習筆記 - - - 簡單方法的使用 (數組)

數組的定義數組

        1. 無索引方法函數

            $list = array("test","test1","test2","test3");spa

            該方法定義的數組默認索引從0開始排序

        2. 有索引索引

            $list = array(
                1 => "test",three

                2 => "test1",內存

                3 => "test2",字符串

                4 => "test3"it

            );test

            該方法定義的數組默認索引從1開始

            注: 

            1).有索引的定義數組中索引能夠爲字符串

            2).打印數組不能使用print, 須要使用print_r打印數組

                var_dump()函數會將數組以詳細的方法輸出

            3).

            $list = array(
                1 => "test",

                 "test1",

                 "test2",

                 "test3"

            );

            該定義方法與有索引定義的例子相同

        3. range函數

            $list = range(1,10);// 限定數組範圍在1到10 之間

            $list = range('a','z');// 限定數組方位在a~z之間

            注:

            在PHP5中range函數有一個新的使用方法

            $list = range(0,10,2);// 限定數組方位在1到10 之間,每次增長2

            $list = (0,2,4,6,8,10);


獲取數組的長度

        count($list);


刪除數組元素或數組

    1. unset();

        舉個例子:

        $list = array('1','2','3','4','5');

        unset($list[2]);

        $list的值爲['1','2','4','5']

        若是對整個數組使用unset方法,會清空真個數組

    2. reset();

        清空數組

    注:

    unset與reset的區別在於

    unset會清空數組相關的變量和內存,而reset只會將數組中的值清空,變量還存在.


數組合並:

    1. array_merge();

        array_merge($list1, $list2);

    2. $lists = $list1 + $list2


數組排序:

    1. sort($list); //只考慮值,不考慮鍵,對值進行排序

    2. rsort($list);// 只考慮值,不考慮鍵,對值進行倒敘排序

    3. asort($list);// 對值進行排序,可是會保持鍵值對應

    4. arsort($list);// 對值進行倒敘排序,會保持鍵值對應

    5. ksort($list);// 對鍵進行排序,會保持鍵值對應

    6. krsort($list);// 對鍵進行排序,會保持鍵值對應



字符串與數組的相互轉換:

     1. 將字符串轉換成數組

         $list = explode("字符串分隔符","字符串");

     2. 將數組轉換爲字符串

         $str = implode("分隔符","數組");


list方法

    用於將數組元素的值賦予給單獨的變量

    例如:

    $list = array("1","2","3");

    list($one, $two, $three) = $list;

    print $one . ' ' . $two . ' ' .$three;

輸出值爲: 1 2 3

注:

    list函數只對數值型索引並從0開始的數組有做用

    使用list函數時,必須確認接收到了每個數組元素,可是接收的變量能夠爲空

相關文章
相關標籤/搜索