項目開發中常用的PHP函數

來源:互聯網
上載者:User

標籤:style   color   使用   strong   io   art   

日期操作

為了便於儲存、比較和傳遞,我們通常需要使用strtotime()函數將日期轉換成UNIX時間戳記,只有在顯示給使用者看的時候才使用date()函數將日期轉換成常用的時間格式。

strtotime()  函數將任何英文文本的日期時間描述解析為 Unix 時間戳記

eg:

<?phpecho(strtotime("now"));echo(strtotime("3 October 2005"));echo(strtotime("+5 hours"));echo(strtotime("+1 week"));echo(strtotime("+1 week 3 days 7 hours 5 seconds"));echo(strtotime("next Monday"));echo(strtotime("last Sunday"));?>

輸出:

1138614504
1128290400
1138632504
1139219304
1139503709
1139180400
1138489200


date()函數 將時間戳記轉換成常用的日期格式

eg:

echo date(‘Y-m-d H:i:s‘,"1138614504");

輸出:

2006-01-30 17:48:24


字串操作

有時候需要取得某個字串的一部分,就需要用到字串的截取substr()函數

substr()函數返回字串的一部分

文法:

substr(string,start,length)

eg:

echo substr("Hello world!",6,5);

輸出:

world


數組操作

這裡介紹兩個非常實用的函數:

array_unique()移除數組中相同元素的個數

當幾個數組元素的值相等時,只保留第一個元素,其他的元素被刪除。
返回的數組中鍵名不變。


array_filter()刪除數組中為空白的元素

文法:

array array_filter ( array $input [, callable $callback = "" ] )

依次將 input 數組中的每個值傳遞到 callback 函數。如果 callback 函數返回 TRUE,則 input 數組的當前值會被包含在返回的結果數組中。數組的鍵名保留不變。

input為要迴圈的數組
callback為使用的回呼函數,如果沒有提供 callback 函數,將刪除 input 中所有等值為 FALSE 的條目(可以利用這條刪除數組中為空白的元素)。

eg1:

<?phpfunction odd($var){    return($var & 1);}$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);echo "Odd :\n";print_r(array_filter($array1, "odd"));?>

輸出:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)

eg2:

<?php$entry = array(             0 => 'foo',             1 => false,             2 => -1,             3 => null,             4 => ''          );print_r(array_filter($entry));?>

輸出:

Array
(
    [0] => foo
    [2] => -1
)


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.