每日五个 PHP 函数记忆
@这是小豪的第六篇文章(其实也不算文章哈哈)
差不多是 2017 年年底的时候接触的 PHP,也没有系统正式的学习过任何基础,当时直接上手了一个 Thinkphp5.0 的商城项目,还是二次开发,在之后的时间里我所有的 PHP 开发思维全部固化在第一个项目里面,模仿….一味的模仿,项目开发框架也一直是 Thinkphp5.0,没有任何改变。
在四个月前,我依然是这样。就连项目中出现的 PHP 函数也只是自己所熟悉的函数的组合,没有愿意去发掘新的自己所不熟知的东西,一直这样,学习也是,东学西学,啥也没学到。
我都知道自己的问题所在,但是总是不愿意跳出自己的舒适区,总以自己还年轻,可以慢慢来当作借口,其实都是屁话。
一直没有进步……..
来到新的公司遇到了超哥,很幸运,很幸运,多的话不说了哈哈。
超哥给了我几点建议:
1. 记 PHP 函数
2. 学习优秀代码的思想
3. 不停写代码,十万行代码什么时候达到什么时候就 NB 了
4. 多尝试脱离任何固定思维去写东西、按自己的想法去做、然后你会遇到问题,总结起来
5. 反思自己写代码的套路与流程,敢于怀疑
一步一个脚印,稳扎稳打,重新出发!从基本的函数记忆开始,坚持 ing!
每天花 5 分钟左右的时间刷一遍,哈哈。
这篇文章已经更新不动了,请戳《每日五个 PHP 函数 (2)》
2019/02/19
- ** 今日小练习 **
// 说明:确保指定 user_id 存在于 users 数组中
$users = array(2, 3);
$user_id = 1;
** in_array($user_id, $users) || array_unshift($users, $user_id); **
print_r($users);
// 输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
—————————————** 回顾 01-15 (点我) **—————————————
2019/02/18
- ** 今日小练习 **
// 说明:将数组以指定字符拼接为字符串、根据指定字符将字符串打散为数组、根据长度将字符串拆分为数组
$arr = array('Hello','World!','I','love','Shenzhen!');
$str = "Hello World! I love Shenzhen!";
** echo implode(“ “, $arr); **
** print_r (explode(“ “, $str)); **
** print_r (str_split($str, 4)); **
// 输出:
Hello World! I love Shenzhen!
// 输出:
(
[0] => Hello
[1] => World!
[2] => I
[3] => love
[4] => Shenzhen!
)
// 输出:
(
[0] => Hell
[1] => o Wo
[2] => rld!
[3] => I l
[4] => ove
[5] => Shen
[6] => zhen
[7] => !
)
—————————————** 回顾 01-14 (点我) **—————————————
2019/02/17
继续回顾之前的噢
- ** 今日小练习 **
// 说明:获取一堆用户中指定 uid 的键值
** $key = array_search(40489, array_column$users, ‘uid’)); **
—————————————** 回顾 01-13 (点我) **—————————————
2019/02/16
继续回顾之前的噢,哈哈
- ** 今日小练习 **
// 说明:时间戳相互转换
** echo date(“Y-m-d H:i”, time()); **
** echo strtotime(“2019-02-16 20:33”); **
// 输出:2019-02-16 20:33
// 输出:1550320380
—————————————** 回顾 01-12 (点我) **—————————————
2019/02/15
继续回顾之前的噢,哈哈
- ** 今日小练习 **
// 说明:获取 abc.jpeg 后缀名
$fileName = 'abc.jpeg';
** echo substr($fileName, strrpos$fileName, “.”)); **
// 输出:.jpeg
—————————————** 回顾 01-11 (点我) **—————————————
2019/02/14
也刷了这么多天的函数了,感觉之前的都忘记了哈哈,现在就回顾一下之前的吧。
- ** 今日小练习 **
// 说明:将 [1, 2, 3] 转变为:[1=>"a", 2=>"a", 3=>"a"]
$arr = array(1, 2, 3);
** var_dump(array_combine($arr, array_fill(0, count($arr), ‘a’))); **
// 输出:
array(3) {
[1]=>
string(1) "a"
[2]=>
string(1) "a"
[3]=>
string(1) "a"
}
—————————————** 回顾 01-10 (点我) **—————————————
2019/02/13
文件系统 No.1
- **
chdir
— 改变目录 **
// 说明:chdir ( string $directory ) : bool
// 将 PHP 的当前目录改为 directory。
- **
chroot
— 改变根目录**
// 说明:chroot ( string $directory ) : bool
// 将当前进程的根目录改变为 directory ,本函数仅在系统支持且运行于 CLI,CGI 或嵌入 SAPI 版本时才能正确工作。此外本函数还需要 root 权限。
- **
closedir
— 关闭目录句柄 **
// 说明:closedir ([ resource $dir_handle ] ) : void
// 关闭由 dir_handle 指定的目录流。流必须之前被 opendir() 所打开。
- **
dir
—返回一个 Directory 类实例 **
// 说明:dir ( string $directory [, resource $context ] ) : Directory
// 以面向对象的方式访问目录。打开 directory 参数指定的目录。
- **
getcwd
— 取得当前工作目录**
// 说明:getcwd ( void ) : string
// 取得当前工作目录
2019/02/12
日期函数 No.3
- **
localtime
— 取得本地时间 **
// 说明:localtime ([ int $timestamp = time() [, bool $is_associative = false ]] ) : array
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
// 输出:
Array
(
[0] => 53
[1] => 46
[2] => 22
[3] => 12
[4] => 1
[5] => 119 // 1900 + 119 = 2019
[6] => 2
[7] => 42
[8] => 0
)
Array
(
[tm_sec] => 53
[tm_min] => 46
[tm_hour] => 22
[tm_mday] => 12
[tm_mon] => 1
[tm_year] => 119
[tm_wday] => 2
[tm_yday] => 42
[tm_isdst] => 0
)
- **
time
— 返回当前的 Unix 时间戳**
// 说明:time ( void ) : int
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now: '. date('Y-m-d') ."\n"; // 输出:Now: 2019-02-12
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n"; // 输出:Next Week: 2019-02-19
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n"; // 输出:Next Week: 2019-02-19
- **
gmdate
— 格式化一个 GMT/UTC 日期/时间 **
// 说明:gmdate ( string $format [, int $timestamp ] ) : string
echo date("M d Y H:i:s", mktime (0,0,0,02,12,2019)); // 输出:Feb 12 2019 00:00:00
echo gmdate("M d Y H:i:s", mktime (0,0,0,02,12,2019)); // 输出:Feb 12 2019 00:00:00
- **
gettimeofday
—取得当前时间 **
// 说明:gettimeofday ([ bool $return_float = false ] ) : mixed
print_r(gettimeofday());
echo gettimeofday(true);
// 输出:
Array
(
[sec] => 1549983633
[usec] => 757476
[minuteswest] => 0
[dsttime] => 0
)
1549983633.7576
- **
gmmktime
— 取得 GMT 日期的 UNIX 时间戳**
// 说明:gmmktime ([ int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst ]]]]]]] ) : int
echo gmmktime(0, 0, 0, 2, 12, 2019); // 输出:1549929600
2019/02/11
日期函数 No.2
- **
date
— 格式化一个本地时间/日期 **
// 说明:date ( string $format [, int $timestamp ] ) : string
// 星期几
echo date("l") . "<br>"; // 输出:Monday
echo date("Y-m-d H:i"); // 输出:2019-02-11 19:48
详细参数说明请戳 -> date 官方文档
- **
strtotime
— 将任何字符串的日期时间描述解析为 Unix 时间戳**
// 说明:strtotime ( string $time [, int $now = time() ] ) : int
echo strtotime("now"), "\n"; // 输出:1549885944
echo strtotime("10 September 2000"), "\n"; // 输出:968515200
echo strtotime("+1 day"), "\n"; // 输出:1549972344
echo strtotime("+1 week"), "\n"; // 输出:1550490744
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n"; // 输出:1550677946
echo strtotime("next Thursday"), "\n"; // 输出:1550073600
echo strtotime("last Monday"), "\n"; // 输出:1549209600
echo strtotime("2019-02-11"), "\n"; // 输出:1549814400
- **
getdate
—取得日期/时间信息 **
// 说明:getdate ([ int $timestamp = time() ] ) : array
$today = getdate();
print_r($today);
// 输出:
Array
(
[seconds] => 9
[minutes] => 58
[hours] => 19
[mday] => 11
[wday] => 1
[mon] => 2
[year] => 2019
[yday] => 41
[weekday] => Monday
[month] => February
[0] => 1549886289
)
- **
microtime
— 返回当前 Unix 时间戳和微秒数 **
// 说明:microtime ([ bool $get_as_float ] ) : mixed
// 如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的
echo(microtime()); // 输出:0.85606500 1549886401
- **
mktime
— 取得一个日期的 Unix 时间戳**
// 说明:mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] ) : int
// 设置要使用的默认时区。 自PHP 5.1起可用
date_default_timezone_set('UTC');
// 输出: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
// 输出: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
2019/02/10
日期函数 No.1
- **
date_create / DateTime::__construct
— 函数返回一个新的 DateTime 对象 **
// 面对对象风格:public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
// 过程化风格:date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTime
$date=date_create("2019-02-10");
echo date_format($date,"Y/m/d"); // 输出:2019/02/10
- **
checkdate
— 检查一些日期是否是有效的格利高里日期**
// 说明:checkdate ( int $month , int $day , int $year ) : bool
// 检查由参数构成的日期的合法性。如果每个参数都正确定义了则会被认为是有效的。
var_dump(checkdate(12, 31, 2000)); // 输出:bool(true)
var_dump(checkdate(2, 29, 2001)); // 输出:bool(false)
- **
date_format
—函数返回一个根据指定格式进行格式化的日期 **
// 面对对象风格:public DateTime::format ( string $format ) : string、public DateTimeImmutable::format ( string $format ) : string、public DateTimeInterface::format ( string $format ) : string
// 过程化风格:date_format ( DateTimeInterface $object , string $format ) : string
$date = new DateTime('2019-02-10');
echo $date->format('Y-m-d H:i:s'); // 输出:2019-02-10 00:00:00
$date = date_create('2019-02-10');
echo date_format($date, 'Y-m-d H:i:s'); // 输出:2019-02-10 00:00:00
- **
date_add / DateTime::add
— 给一个 DateTime 对象增加一定量的天,月,年,小时,分钟 以及秒 **
// 面对对象风格:public DateTime::add ( DateInterval $interval ) : DateTime
// 过程化风格:date_add ( DateTime $object , DateInterval $interval ) : DateTime
// 添加 40 天到 2013 年 3 月 15 日:
$date=date_create("2019-02-10");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d"); // 输出:2019-03-22
- **
date_interval_create_from_date_string / DateInterval::createFromDateString()
— 从字符串的相关部分建立一个 DateInterval**
// 说明:public static DateInterval::createFromDateString ( string $time ) : DateInterval
2019/02/08
日历函数 No.2
- **
JDToGregorian
— 转变一个Julian Day计数为Gregorian历法日期**
// 说明:jdtogregorian ( int $julianday ) : string
- **
gregoriantojd
— 转变一个 Gregorian 历法日期到 Julian Day 计数**
// 说明:gregoriantojd ( int $month , int $day , int $year ) : int
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n"; // 输出:2440871
$gregorian = JDToGregorian($jd);
echo "$gregorian\n"; // 输出:10/11/1970
- **
JDMonthName
— 返回月份的名称 **
// 说明:jdmonthname ( int $julianday , int $mode ) : string
$jd=gregoriantojd(1,13,1998);
echo jdmonthname($jd,0);
- **
jdtounix
—转变 Julian Day 计数为一个 Unix 时间戳**
// 说明:jdtounix ( int $jday ) : int
// 这个函数根据给定的 julian 天数返回一个Unix时间戳,或如果参数 jday 不在 Unix 时间( Gregorian 历法的 1970 年至 2037 年,或 2440588 <= jday <= 2465342)范围内返回 FALSE 。返回的时间是本地时间(不是 GMT )。
- **
unixtojd
— 转变 Unix 时间戳为 Julian Day 计数**
// 说明:unixtojd ([ int $timestamp = time() ] ) : int
// 根据指定的Unix时间戳 timestamp,返回 Julian 天数。如果没有指定时间戳则返回当前日期的天数
2019/02/07
日历函数 No.1
- **
cal_info
— 返回选定历法的信息**
// 说明:cal_info ([ int $calendar = -1 ] ) : array
// 0 or CAL_GREGORIAN - 阳历
// 1 or CAL_JULIAN - 儒略日(是在儒略周期内以连续的日数计算时间的计时法,主要是天文学家在使用。)
// 2 or CAL_JEWISH - 犹太历;犹历(犹太人所用的一种阴阳历记日系统,从公元前3761年算起)
// 3 or CAL_FRENCH - 法国共和历(法兰西第一共和国采用的革命历法,于1793年11月24日起采用,1806年元旦废止)
$info = cal_info(0);
print_r($info);
// 输出:
Array
(
[months] => Array
(
[1] => January
[2] => February
[3] => March
[4] => April
[5] => May
[6] => June
[7] => July
[8] => August
[9] => September
[10] => October
[11] => November
[12] => December
)
[abbrevmonths] => Array
(
[1] => Jan
[2] => Feb
[3] => Mar
[4] => Apr
[5] => May
[6] => Jun
[7] => Jul
[8] => Aug
[9] => Sep
[10] => Oct
[11] => Nov
[12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] => CAL_GREGORIAN
)
- **
cal_days_in_month
— 返回某个历法中某年中某月的天数**
// 说明:cal_days_in_month ( int $calendar , int $month , int $year ) : int
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
- **
easter_date
— 得到指定年份的复活节午夜时的Unix时间戳 **
// 说明:easter_date ([ int $year ] ) : int
echo date("M-d-Y", easter_date(1999)); // Apr-04-1999
echo date("M-d-Y", easter_date(2000)); // Apr-23-2000
echo date("M-d-Y", easter_date(2001)); // Apr-15-2001
- **
easter_days
— 得到指定年份的3月21日到复活节之间的天数**
// 说明:easter_days ([ int $year [, int $method = CAL_EASTER_DEFAULT ]] ) : int
// 返回指定年份的3月21日到复活节之间的天数,如果没有指定年份,默认是当年。
echo easter_days(1999); // 14, i.e. April 4
echo easter_days(1492); // 32, i.e. April 22
echo easter_days(1913); // 2, i.e. March 23
- **
JDDayOfWeek
— 返回星期的日期**
// 说明:jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] ) : mixed
// mode:
// 0 -> 返回数字形式(0=Sunday, 1=Monday, etc)
// 1 -> 返回字符串形式 (English-Gregorian)
// 2 -> 返回缩写形式的字符串 (English-Gregorian)
// 返回 1998 年 1 月 13 日这天是周几:
$jd=gregoriantojd(1,13,1998); // gregoriantojd:转变一个 Gregorian 历法日期到 Julian Day 计数
echo jddayofweek($jd,1); // 输出:Tuesday
2019/02/06
过滤器函数 No.1
- **
filter_has_var
— 检测是否存在指定类型的变量**
// 说明:filter_has_var ( int $type , string $variable_name ) : bool
if ( !filter_has_var(INPUT_GET, 'email') ) {
echo "Email Not Found";
}else{
echo "Email Found";
}
localhost/test.php?email=1 //Email Found
localhost/test.php?email //Email Found
localhost/test.php //Email Not Found
- **
filter_list
— 返回所支持的过滤器列表**
// 说明:filter_list ( void ) : array
print_r(filter_list());
// 输出类似:
Array
(
[0] => int
[1] => boolean
[2] => float
[3] => validate_regexp
[4] => validate_url
[5] => validate_email
[6] => validate_ip
[7] => string
[8] => stripped
[9] => encoded
[10] => special_chars
[11] => unsafe_raw
[12] => email
[13] => url
[14] => number_int
[15] => number_float
[16] => magic_quotes
[17] => callback
)
- **
filter_id
— 返回与某个特定名称的过滤器相关联的 id **
// 说明:filter_id ( string $filtername ) : int
$filters = filter_list();
foreach($filters as $filter_name) {
echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
// 输出类似:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024
- **
filter_input
— 通过名称获取特定的外部变量,并且可以通过过滤器处理它**
// 说明:filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed
// type: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER或 INPUT_ENV之一。
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n"; // 输出:You have searched for Me & son.
echo "<a href='?search=$search_url'>Search again.</a>"; // 输出:<a href='?search=Me%20%26%20son'>Search again.</a>
- **
filter_var
— 使用特定的过滤器过滤一个变量**
// 说明:filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); // 输出:string(15) "bob@example.com"
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)); // 输出:bool(false)
2019/02/05
可变处理函数 No.4
- **
is_string
— 检测变量是否是字符串**
// 说明:is_string ( mixed $var ) : bool
- **
isset
— 检测变量是否已设置并且非 NULL**
// 说明:isset ( mixed $var [, mixed $... ] ) : bool
$var = '';
// 结果为 TRUE,所以后边的文本将被打印出来。
if (isset($var)) {
echo "This var is set so I will print.";
}
$a = "test";
$b = "anothertest";
var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a)); // FALSE
var_dump(isset($a, $b)); // FALSE
$foo = NULL;
var_dump(isset($foo)); // FALSE
- **
serialize
— 产生一个可存储的值的表示**
// 说明:serialize ( mixed $value ) : string
// serialize() 返回字符串,此字符串包含了表示 value 的字节流,可以存储于任何地方
- **
unserialize
— 从已存储的表示中创建 PHP 的值**
// 说明:unserialize ( string $str ) : mixed
// unserialize() 对单一的已序列化的变量进行操作,将其转换回 PHP 的值。
- **
unset
— 释放给定的变量**
// 说明:unset ( mixed $var [, mixed $... ] ) : void
// unset() 销毁指定的变量。
2019/02/04
可变处理函数 No.3
- **
is_float / is_double
— 检测变量是否是浮点型**
// 说明:is_float ( mixed $var ) : bool
- **
is_int / is_integer / is_long
— 检测变量是否是整数**
// 说明:is_int ( mixed $var ) : bool
- **
is_null
— 检测变量是否为 NULL**
// 说明:is_null ( mixed $var ) : bool
- **
is_numeric
— 检测变量是否为数字或数字字符串**
// 说明:is_numeric ( mixed $var ) : bool
- **
is_object
— 检测变量是否是一个对象**
// 说明:is_object ( mixed $var ) : bool
哈哈,今天新年啦,祝福大家新年快乐,身体棒棒哒!
2019/02/03
可变处理函数 No.2
- **
get_resource_type
— 返回资源(resource)类型**
// 说明:get_resource_type ( resource $handle ) : string
$c = mysql_connect();
echo get_resource_type($c)."\n"; // 输出:mysql link
$fp = fopen("foo","w");
echo get_resource_type($fp)."\n"; // 输出:file
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc)."\n"; // 输出:domxml document
- **
is_array
— 检测变量是否是数组**
// 说明:is_array ( mixed $var ) : bool
// 如果 var 是 array,则返回 TRUE,否则返回 FALSE。
- **
is_bool
— 检测变量是否是布尔型**
// 说明:is_bool ( mixed $var ) : bool
// 如果 var 是 boolean 则返回 TRUE。
- **
is_callable
— 检测参数是否为合法的可调用结构**
// 说明:is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] ) : bool
// name:要检查的回调函数。
// syntax_only:如果设置为 TRUE,这个函数仅仅验证 name 可能是函数或方法。 它仅仅拒绝非字符,或者未包含能用于回调函数的有效结构。有效的应该包含两个元素,第一个是一个对象或者字符,第二个元素是个字符。
// callable_name 接受“可调用的名称”。下面的例子是 “someClass::someMethod” 。 注意,尽管 someClass::SomeMethod() 的含义是可调用的静态方法,但例子的情况并不是这样的。
function someFunction()
{
}
$functionVariable = 'someFunction';
var_dump(is_callable($functionVariable, false, $callable_name)); // bool(true)
echo $callable_name, "\n"; // someFunction
//
// Array containing a method
//
class someClass {
function someMethod()
{
}
}
$anObject = new someClass();
$methodVariable = array($anObject, 'someMethod');
var_dump(is_callable($methodVariable, true, $callable_name)); // bool(true)
echo $callable_name, "\n"; // someClass::someMethod
- **
is_countable
— 验证变量的内容是否为可数值**
// 说明:is_countable ( mixed $var ) : bool
var_dump(is_countable([1, 2, 3])); // bool(true)
var_dump(is_countable(new ArrayIterator(['foo', 'bar', 'baz']))); // bool(true)
var_dump(is_countable(new ArrayIterator())); // bool(true)
var_dump(is_countable(new stdClass())); // bool(false)
2019/02/02
可变处理函数 No.1
- **
boolval
— 获取变量的布尔值**
// 说明:boolval ( mixed $var ) : boolean
echo '0: '.(boolval(0) ? 'true' : 'false')."\n"; // 输出:0: false
echo '42: '.(boolval(42) ? 'true' : 'false')."\n"; // 输出:42: true
echo '0.0: '.(boolval(0.0) ? 'true' : 'false')."\n"; // 输出:0.0: false
echo '4.2: '.(boolval(4.2) ? 'true' : 'false')."\n"; // 输出:4.2: true
echo '"": '.(boolval("") ? 'true' : 'false')."\n"; // 输出:"": false
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n"; // 输出:"string": true
echo '"0": '.(boolval("0") ? 'true' : 'false')."\n"; // 输出:"0": false
echo '"1": '.(boolval("1") ? 'true' : 'false')."\n"; // 输出:"1": true
echo '[1, 2]: '.(boolval([1, 2]) ? 'true' : 'false')."\n"; // 输出:[1, 2]: true
echo '[]: '.(boolval([]) ? 'true' : 'false')."\n"; // 输出:[]: false
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n"; // 输出:stdClass: true
- **
floatval
— 获取变量的浮点值**
// 说明:floatval ( mixed $var ) : float
$var = '122.34343The';
$float_value_of_var = floatval ($var);
print $float_value_of_var; // 输出: 122.34343
- **
intval
— 获取变量的整数值**
// 说明:intval ( mixed $var [, int $base = 10 ] ) : int
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
- **
strval
— 获取变量的字符串值**
// 说明:strval ( mixed $var ) : string
$foo = strval(123);
var_dump($foo); // string(3) "123"
- **
settype
— 设置变量的类型**
// 说明:settype ( mixed &$var , string $type ) : bool
$foo = "5bar"; // string
$bar = true; // boolean
settype($foo, "integer"); // $foo 现在是 5 (integer)
settype($bar, "string"); // $bar 现在是 "1" (string)
2019/02/01
Ctype 函数 No.2
- **
ctype_lower
— 做小写字符检测**
// 说明:ctype_lower ( string $text ) : bool
// 检查提供的 string 和 text 里面的字符是不是都是小写字母。
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
if (ctype_lower($testcase)) {
echo "The string $testcase consists of all lowercase letters.\n";
} else {
echo "The string $testcase does not consist of all lowercase letters.\n";
}
}
// 输出:
// The string aac123 does not consist of all lowercase letters.
// The string qiutoas consists of all lowercase letters.
// The string QASsdks does not consist of all lowercase letters.
- **
ctype_print
— 做可打印字符检测**
// 说明:ctype_print ( string $text ) : bool
// 检查提供的 string 和 text 里面的字符是不是都是可以打印出来。
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
if (ctype_print($testcase)) {
echo "The string '$name' consists of all printable characters.\n";
} else {
echo "The string '$name' does not consist of all printable characters.\n";
}
}
// 输出:
// The string 'string1' does not consist of all printable characters.
// The string 'string2' consists of all printable characters.
// The string 'string3' consists of all printable characters.
- **
ctype_punct
— 检测可打印的字符是不是不包含空白、数字和字母**
// 说明:ctype_punct ( string $text ) : bool
// 检查提供的 string 和 text 里面的字符是不是都是标点符号。
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
if (ctype_punct($testcase)) {
echo "The string $testcase consists of all punctuation.\n";
} else {
echo "The string $testcase does not consist of all punctuation.\n";
}
}
// 输出:
// The string ABasdk!@!$# does not consist of all punctuation.
// The string !@ # $ does not consist of all punctuation.
// The string *&$() consists of all punctuation.
- **
ctype_space
— 做空白字符检测**
// 说明:ctype_space ( string $text ) : bool
// 检查提供的 string 和 text 里面的字符是否包含空白。
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
if (ctype_space($testcase)) {
echo "The string '$name' consists of all whitespace characters.\n";
} else {
echo "The string '$name' does not consist of all whitespace characters.\n";
}
}
// 输出:
// The string 'string1' consists of all whitespace characters.
// The string 'string2' does not consist of all whitespace characters.
// The string 'string3' does not consist of all whitespace characters.
- **
ctype_upper
— 做大写字母检测**
// 说明:ctype_upper ( string $text ) : bool
// 检查 string 和 text 里面的字符是不是都是大写字母。
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
if (ctype_upper($testcase)) {
echo "The string $testcase consists of all uppercase letters.\n";
} else {
echo "The string $testcase does not consist of all uppercase letters.\n";
}
}
// 输出:
// The string AKLWC139 does not consist of all uppercase letters.
// The string LMNSDO consists of all uppercase letters.
// The string akwSKWsm does not consist of all uppercase letters.
2019/01/31
Ctype 函数 No.1
- **
ctype_alnum
— 做字母和数字字符检测**
// 说明:ctype_alnum ( string $text ) : bool
// 如果 text 中所有的字符全部是字母和(或者)数字,返回 TRUE 否则返回 FALSE
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
// 输出:
// The string AbCd1zyZ9 consists of all letters or digits.
// The string foo!#$bar does not consist of all letters or digits.
- **
ctype_alpha
— 做纯字符检测**
// 说明:ctype_alpha ( string $text ) : bool
// 如果在当前语言环境中 text 里的每个字符都是一个字母,那么就返回 TRUE,反之则返回 FALSE。
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
if (ctype_alpha($testcase)) {
echo "The string $testcase consists of all letters.\n";
} else {
echo "The string $testcase does not consist of all letters.\n";
}
}
// 输出:
// The string KjgWZC consists of all letters.
// The string arf12 does not consist of all letters.
- **
ctype_cntrl
— 做控制字符检测**
// 说明:ctype_cntrl ( string $text ) : bool
// 如果在当前的语言环境下 text 里面的每个字符都是控制字符,就返回 TRUE ;反之就返回 FALSE 。
// 控制字符就是例如:换行、缩进、空格。
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
if (ctype_cntrl($testcase)) {
echo "The string '$name' consists of all control characters.\n";
} else {
echo "The string '$name' does not consist of all control characters.\n";
}
}
// 输出:
// The string 'string1' consists of all control characters.
// The string 'string2' does not consist of all control characters.
- **
ctype_digit
— 做纯数字检测**
// 说明:ctype_digit ( string $text ) : bool
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
// 输出:
// The string 1820.20 does not consist of all digits.
// The string 10002 consists of all digits.
// The string wsl!12 does not consist of all digits.
- **
ctype_graph
— 做可打印字符串检测,空格除外**
// 说明:ctype_graph ( string $text ) : bool
// 如果 text 里面的每个字符都是输出可见的(没有空白),就返回 TRUE ;反之就返回 FALSE 。
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
if (ctype_graph($testcase)) {
echo "The string '$name' consists of all (visibly) printable characters.\n";
} else {
echo "The string '$name' does not consist of all (visibly) printable characters.\n";
}
}
// 输出:
// The string 'string1' does not consist of all (visibly) printable characters.
// The string 'string2' consists of all (visibly) printable characters.
// The string 'string3' consists of all (visibly) printable characters.
2019/01/30
类/对象 函数 No.3
- **
is_a
— 如果对象属于该类或该类是此对象的父类则返回 TRUE**
// 说明:is_a ( object $object , string $class_name [, bool $allow_string = FALSE ] ) : bool
// 定义一个类
class WidgetFactory
{
var $oink = 'moo';
}
// 创建一个新对象
$WF = new WidgetFactory();
if (is_a($WF, 'WidgetFactory')) {
echo "yes, \$WF is still a WidgetFactory\n";
}
- **
is_subclass_of
— 如果此对象是该类的子类,则返回 TRUE**
// 说明:is_subclass_of ( object $object , string $class_name ) : bool
// define a class
class WidgetFactory
{
var $oink = 'moo';
}
// define a child class
class WidgetFactory_Child extends WidgetFactory
{
var $oink = 'oink';
}
// create a new object
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();
if (is_subclass_of($WFC, 'WidgetFactory')) {
echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
echo "no, \$WFC is not a subclass of WidgetFactory\n";
}
if (is_subclass_of($WF, 'WidgetFactory')) {
echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
echo "no, \$WF is not a subclass of WidgetFactory\n";
}
// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
// 输出:
// yes, $WFC is a subclass of WidgetFactory
// no, $WF is not a subclass of WidgetFactory
// yes, WidgetFactory_Child is a subclass of WidgetFactory
- **
method_exists
— 检查类的方法是否存在**
// 说明:method_exists ( mixed $object , string $method_name ) : bool
$directory = new Directory('.');
var_dump(method_exists($directory,'read')); // 输出:bool(true)
- **
property_exists
— 检查对象或类是否具有该属性**
// 说明:property_exists ( mixed $class , string $property ) : bool
class myClass {
public $mine;
private $xpto;
static protected $test;
static function test() {
var_dump(property_exists('myClass', 'xpto')); //true
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0
myClass::test();
- **
trait_exists
— 检查指定的 trait 是否存在**
// 说明:trait_exists ( string $traitname [, bool $autoload ] ) : bool
trait World {
private static $instance;
protected $tmp;
public static function World()
{
self::$instance = new static();
self::$instance->tmp = get_called_class().' '.__TRAIT__;
return self::$instance;
}
}
if ( trait_exists( 'World' ) ) {
class Hello {
use World;
public function text( $str )
{
return $this->tmp.$str;
}
}
}
echo Hello::World()->text('!!!'); // Hello World!!!
2019/01/29
类/对象 函数 No.2
- **
get_class_methods
— 返回由类的方法名组成的数组**
// 说明:get_class_methods ( mixed $class_name ) : array
class myclass {
// constructor
function myclass()
{
return(true);
}
// method 1
function myfunc1()
{
return(true);
}
// method 2
function myfunc2()
{
return(true);
}
}
$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) {
echo "$method_name\n";
}
// 输出:myclass、myfunc1、myfunc2
- **
get_class
— 返回对象的类名**
// 说明:get_class ([ object $object = NULL ] ) : string
class foo {
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}
// create an object
$bar = new foo();
// external call
echo "Its name is " , get_class($bar) , "\n"; // 输出:Its name is foo
// internal call
$bar->name(); // 输出:My name is foo
- **
get_class_vars
— 返回由类的默认属性组成的数组**
// 说明:get_class_vars ( string $class_name ) : array
class myclass {
var $var1; // this has no default value...
var $var2 = "xyz";
var $var3 = 100;
private $var4;
// constructor
function __construct() {
// change some properties
$this->var1 = "foo";
$this->var2 = "bar";
return true;
}
}
$my_class = new myclass();
$class_vars = get_class_vars(get_class($my_class));
foreach ($class_vars as $name => $value) {
echo "$name : $value\n";
}
// 输出:var1 : 、var2 : xyz、var3 : 100
- **
get_parent_class
— 返回对象或类的父类名**
// 说明:get_parent_class ([ mixed $obj ] ) : string
class dad {
function dad()
{
// implements some logic
}
}
class child extends dad {
function child()
{
echo "I'm " , get_parent_class($this) , "'s son\n";
}
}
class child2 extends dad {
function child2()
{
echo "I'm " , get_parent_class('child2') , "'s son too\n";
}
}
$foo = new child(); // 输出:I'm dad's son
$bar = new child2(); // 输出:I'm dad's son too
- **
interface_exists
— 检查接口是否已被定义**
// 说明:interface_exists ( string $interface_name [, bool $autoload = true ] ) : bool
// 在尝试使用前先检查接口是否存在
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// Methods
}
}
2019/01/28
类/对象 函数 No.1
- **
__autoload
— 尝试加载未定义的类**
// 说明:__autoload ( string $class ) : void
// index.php
function __autoload($class) {
$file = $class . '.php';
require_once $file;
}
$test = new test();
// test.php
class test {
public function __construct() {
echo "this is test";
}
}
// 当在 index.php 中初始化 test 时,因为找不到对应类,就会调用 __autoload() 引入对应文件。
- **
spl_autoload_register
— 注册给定的函数作为 __autoload 的实现**
// 说明:spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) : bool
// 因为 __autoload() 在一个进程中只能定义它一次。当我们在进行项目合并的时候,如果出现多个 autoload() 需要将其合并为一个函数。那么,出现了 spl_autoload_register()。
// index.php
function autoload_test($class) {
$file = $class . '.php';
require_once $file;
}
spl_autoload_register("autoload_test");
$test = new test();
// test.php
class test {
public function __construct() {
echo "this is test";
}
}
// 使用此函数可以生成一个__autoload()队列,可以注册多个函数。
// index.php
function autoload_test($class) {
$file = $class . '.php';
require_once $file;
}
function autoload_vos($class) {
$file = $class . '.php';
require_once $file;
}
spl_autoload_register("autoload_test");
spl_autoload_register("autoload_vos");
$test = new test();
- **
class_alias
— 为一个类创建别名**
// 说明:class_alias ( string $original , string $alias [, bool $autoload = TRUE ] ) : bool
class foo { }
class_alias('foo', 'bar');
$a = new foo;
$b = new bar;
// the objects are the same
var_dump($a == $b, $a === $b); // 输出:bool(true)
var_dump($a instanceof $b); // 输出:bool(false)
// the classes are the same
var_dump($a instanceof foo); // 输出:bool(true)
var_dump($a instanceof bar); // 输出:bool(true)
var_dump($b instanceof foo); // 输出:bool(true)
var_dump($b instanceof bar); // 输出:bool(true)
- **
class_exists
— 检查类是否已定义**
// 说明:class_exists ( string $class_name [, bool $autoload = true ] ) : bool
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
- **
get_called_class
— 后期静态绑定(”Late Static Binding”)类的名称**
// 说明:get_called_class ( void ) : string
class foo {
static public function test() {
var_dump(get_called_class());
}
}
class bar extends foo {
}
foo::test(); // 输出:string(3) "foo"
bar::test(); // 输出:string(3) "bar"
2019/01/27
Math 函数 No.2
- **
max
— 找出最大值**
// 说明:max ( array $values ) : mixed、max ( mixed $value1 , mixed $value2 [, mixed $... ] ) : mixed
// 如果仅有一个参数且为数组,max() 返回该数组中最大的值。如果第一个参数是整数、字符串或浮点数,则至少需要两个参数而 max() 会返回这些值中最大的一个。可以比较无限多个值。
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
// 当 hello 被转换为整数时转化为了 0 ,两个值相等
echo max(0, 'hello'); // 0
// hello 的长度要比 0 长,所以输出 hello
echo max('hello', 0); // hello
echo max('42', 3); // '42'
// 这里 0 > -1, 所以返回 hello
echo max(-1, 'hello'); // hello
// 多个数组长度不同时,返回长度长的
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)
// 对多个数组,max 从左向右比较。
// 因此在本例中:2 == 2,但 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
// 如果同时给出数组和非数组作为参数,则总是将数组视为
// 最大值返回
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
- **
min
— 找出最小值**
// 说明:min ( array $values ) : mixed、min ( mixed $value1 , mixed $value2 [, mixed $... ] ) : mixed
// 如果仅有一个参数且为数组,min() 返回该数组中最小的值。如果给出了两个或更多参数, min() 会返回这些值中最小的一个。
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0
echo min('hello', 0); // hello
echo min('hello', -1); // -1
// 对多个数组,min 从左向右比较。
// 因此在本例中:2 == 2,但 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
// 如果同时给出数组和非数组作为参数,则不可能返回数组,因为
// 数组被视为最大的
$val = min('string', array(2, 5, 7), 42); // string
- **
mt_rand
— 生成更好的随机数**
// 说明:mt_rand ( void ) : int、mt_rand ( int $min , int $max ) : int
// 很多老的 libc 的随机数发生器具有一些不确定和未知的特性而且很慢。PHP 的 rand() 函数默认使用 libc 随机数发生器。mt_rand() 函数是非正式用来替换它的。该函数用了 » Mersenne Twister 中已知的特性作为随机数发生器,它可以产生随机数值的平均速度比 libc 提供的 rand() 快四倍。
echo mt_rand() . "\n"; // 输出:1604716014
echo mt_rand() . "\n"; // 输出:1478613278
echo mt_rand(5, 15); // 输出:6
- **
mt_getrandmax
— 显示随机数的最大可能值**
// 说明:mt_getrandmax ( void ) : int
// 返回调用 mt_rand() 所能返回的最大的随机数。
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
var_dump(randomFloat()); // 输出:float(0.91601131712832)
var_dump(randomFloat(2, 20)); // 输出:float(16.511210331931)
- **
round
— 对浮点数进行四舍五入**
// 说明:round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] ) : float
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
2019/01/26
Math 函数 No.1
- **
ceil
— 进一法取整**
// 说明:ceil ( float $value ) : float
// 返回不小于 value 的下一个整数,value 如果有小数部分则进一位
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
- **
exp
— 计算 e 的指数**
// 说明:exp ( float $arg ) : float
// 返回 e 的 arg 次方值,用 'e' 作为自然对数的底 2.718282.
echo exp(12) . "\n"; //输出:1.6275E+005
echo exp(5.7); // 输出:298.87
- **
floor
— 舍去法取整**
// 说明:floor ( float $value ) : float
// 返回不大于 value 的最接近的整数,舍去小数部分取整。
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
- **
fmod
— 返回除法的浮点数余数**
// 说明:fmod ( float $x , float $y ) : float
// 返回被除数(x)除以除数(y)所得的浮点数余数。余数(r)的定义是:x = i * y + r,其中 i 是整数。如果 y 是非零值,则 r 和 x 的符号相同并且其数量值小于 y。
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
echo $r; // 输出:0.5 (4 * 1.3 + 0.5 = 5.7)
- **
getrandmax
— 显示随机数最大的可能值**
// 说明:getrandmax ( void ) : int
// 返回调用 rand() 可能返回的最大值。
echo(getrandmax()); // 输出:2147483647
2019/01/25
函数处理 函数
- **
func_num_args
— 返回传递给函数的参数个数**
// 说明:func_num_args ( void ) : int
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
}
foo(1, 2, 3); // 输出:Number of arguments: 3
- **
func_get_arg
— 返回参数列表的某一项**
// 说明:func_get_arg ( int $arg_num ) : mixed
// arg_num:参数的偏移量。函数的参数是从0开始计数的。
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
}
foo (1, 2, 3);
// 输出:
// Number of arguments: 3
// Second argument is: 2
- **
func_get_args
— 返回一个包含函数参数列表的数组**
// 说明:func_get_args ( void ) : array
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
// 输出:
// Number of arguments: 3<br />
// Second argument is: 2<br />
// Argument 0 is: 1<br />
// Argument 1 is: 2<br />
// Argument 2 is: 3<br />
- **
function_exists
— 如果给定的函数已经被定义就返回 TRUE**
// 说明:function_exists ( string $function_name ) : bool
if (function_exists('imap_open')) {
echo "IMAP functions are available.<br />\n";
} else {
echo "IMAP functions are not available.<br />\n";
}
// 输出:IMAP functions are not available.<br />
- **
get_defined_functions
— 返回所有已定义函数的数组**
// 说明:get_defined_functions ([ bool $exclude_disabled = FALSE ] ) : array
// exclude_disabled:禁用的函数是否应该在返回的数据里排除
function myrow($id, $data)
{
return "<tr><th>$id</th><td>$data</td></tr>\n";
}
$arr = get_defined_functions();
print_r($arr);
// 输出:
Array
(
[internal] => Array
(
[0] => zend_version
[1] => func_num_args
[2] => func_get_arg
[3] => func_get_args
[4] => strlen
[5] => strcmp
[6] => strncmp
...
[750] => bcscale
[751] => bccomp
)
[user] => Array
(
[0] => myrow
)
)
2019/01/24
函数处理 函数
- **
call_user_func_array
— 调用回调函数,并把一个数组参数作为回调函数的参数**
// 说明:call_user_func_array ( callable $callback , array $param_arr ) : mixed
function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two")); // 输出:foobar got one and two
// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four")); // 输出:foo::bar got three and four
- **
call_user_func
— 把第一个参数作为回调函数调用**
// 说明:call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) : mixed
function barber($type)
{
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom"); // 输出:You wanted a mushroom haircut, no problem
call_user_func('barber', "shave"); // 输出:You wanted a shave haircut, no problem
- **
create_function
— 创建一个匿名函数**
// 说明:create_function ( string $args , string $code ) : string
// log():返回自然对数
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
// M_E:常量值:2.7182818284590452354
echo $newfunc(2, M_E) . "\n";
// 输出:
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
- **
forward_static_call_array
— 调用静态方法并将参数作为数组传递**
// 说明:forward_static_call_array ( callable $function , array $parameters ) : mixed
class A
{
const NAME = 'A';
public static function test() {
$args = func_get_args();
echo static::NAME, " ".join(',', $args)." \n";
}
}
class B extends A
{
const NAME = 'B';
public static function test() {
echo self::NAME, "\n";
forward_static_call_array(array('A', 'test'), array('more', 'args'));
forward_static_call_array( 'test', array('other', 'args'));
}
}
B::test('foo');
// join:implode 的别名
function test() {
$args = func_get_args();
echo "C ".join(',', $args)." \n";
}
// 输出:
// B
// B more,args
// C other,args
- **
forward_static_call
— 调用静态方法**
// 说明:forward_static_call ( callable $function [, mixed $parameter [, mixed $... ]] ) : mixed
class A
{
const NAME = 'A';
public static function test() {
$args = func_get_args();
echo static::NAME, " ".join(',', $args)." \n";
}
}
class B extends A
{
const NAME = 'B';
public static function test() {
echo self::NAME, "\n";
forward_static_call(array('A', 'test'), 'more', 'args');
forward_static_call( 'test', 'other', 'args');
}
}
B::test('foo');
function test() {
$args = func_get_args();
echo "C ".join(',', $args)." \n";
}
// 输出:
// B
// B more,args
// C other,args
2019/01/23
字符串相关函数 No.2
- **
sscanf
— 根据指定格式解析输入的字符**
// 说明:sscanf ( string $str , string $format [, mixed &$... ] ) : mixed
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
// 输出:Item 2350001 was manufactured on: 2000-Jan-1
- **
strlen
— 获取字符串长度**
// 说明:strlen ( string $string ) : int
$str = 'abcdef';
echo strlen($str); // 6
$str = ' ab cd ';
echo strlen($str); // 7
- **
strpbrk
— 在字符串中查找一组字符的任何一个字符**
// 说明:strpbrk ( string $haystack , string $char_list ) : string
$text = 'This is a Simple text.';
// 输出 "is is a Simple text.",因为 'i' 先被匹配
echo strpbrk($text, 'mi');
// 输出 "Simple text.",因为字符区分大小写
echo strpbrk($text, 'S');
- **
preg_match
— 执行匹配正则表达式**
// 说明:preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int
// 从URL中获取主机名称
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.runoob.com/index.html", $matches);
$host = $matches[1];
// 获取主机名称的后面两部分
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
// 输出:domain name is: runoob.com
- **
wordwrap
— 打断字符串为指定数量的字串**
// 说明:wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] ) : string
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "、");
echo $newtext;
// 输出:The quick brown fox、jumped over the lazy、dog.
2019/01/22
字符串相关函数 No.1
- **
sprintf
— 返回格式化的字符串**
// 说明:sprintf ( string $format [, mixed $... ] ) : string
// string - s
// integer - d, u, c, o, x, X, b
// double - g, G, e, E, f, F
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location); // 输出:"There are 5 monkeys in the tree"
// 指定顺序
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);// 输出:"The tree contains 5 monkeys"
- **
ltrim
— 删除字符串开头的空白字符(或其他字符)**
// 说明:ltrim ( string $str [, string $character_mask ] ) : string
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
$trimmed = ltrim($text);
echo $trimmed; // 输出:"These are a few words :) ... "
$trimmed = ltrim($text, " \t.");
var_dump($trimmed);// 输出:"These are a few words :) ... "
$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);// 输出:"o World"
// 删除 $binary 开头的 ASCII 控制字符
// (从 0 到 31,包括 0 和 31)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);// 输出:"These are a few words :) ... "
// trim、ltrim、rtrim 都是类似的:左右都过滤、左过滤、右过滤
- **
strtolower
— 将字符串转化为小写**
// 说明:strtolower ( string $string ) : string
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // 打印 mary had a little lamb and she loved it so
- **
strtoupper
— 将字符串转化为大写**
// 说明:strtoupper ( string $string ) : string
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // 打印 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
- **
strtok
— 标记分割字符串**
// 说明:strtok ( string $str , string $token ) : string 、strtok ( string $token ) : string
$string = "This is\tan example\nstring";
// 注意仅第一次调用 strtok 函数时使用 string 参数。后来每次调用 strtok,都将只使用 token 参数,因为它会记住它在字符串 string 中的位置。如果要重新开始分割一个新的字符串,你需要再次使用 string 来调用 strtok 函数,以便完成初始化工作。注意可以在 token 参数中使用多个字符。字符串将被该参数中任何一个字符分割。
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok";
$tok = strtok(" \n\t");
}
// 输出:Word=This Word=is Word=an Word=example Word=string
$first_token = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token); // 输出: string(9) "something" 、 bool(false)
2019/01/21
数组相关函数 No.6
- **
array_key_exists
— 检查数组里是否有指定的键名或索引**
// 说明:array_key_exists ( mixed $key , array $array ) : bool
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
// array_key_exists() 与 isset() 的对比
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
- **
key
— 从关联数组中取得键名**
// 说明:key ( array $array ) : mixed
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array);
}
next($array);
}
// 输出:fruit1、fruit4、fruit5
- **
sort
— 对数组排序**
// 说明:sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
/**
* sort_flags:第二个参数介绍
*
* SORT_REGULAR - 正常比较单元(不改变类型)
* SORT_NUMERIC - 单元被作为数字来比较
* SORT_STRING - 单元被作为字符串来比较
* SORT_LOCALE_STRING - 根据当前的区域(locale)设置来把单元当作字符串比较,可以用 setlocale() 来改变。
* SORT_NATURAL - 和 natsort() 类似对每个单元以“自然的顺序”对字符串进行排序。 PHP 5.4.0 中新增的。
* SORT_NATURAL - 和 natsort() 类似对每个单元以“自然的顺序”对字符串进行排序。 PHP 5.4.0 中新增的。
*/
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
// 输出:fruits[0] = apple、fruits[1] = banana、fruits[2] = lemon、fruits[3] = orange
// 带 sort_flags 参数:
$fruits = array(
"Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
// 输出:fruits[0] = Orange1、fruits[1] = orange2、fruits[2] = Orange3、fruits[3] = orange20
- **
natcasesort
— 用“自然排序”算法对数组进行不区分大小写字母的排序**
// 说明:natcasesort ( array &$array ) : bool
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');
sort($array1);
print_r($array1); // 输出:['IMG0.png', 'IMG3.png', 'img1.png', 'img10.png', 'img12.png', 'img2.png']
natcasesort($array2);
print_r($array2); // 输出:['IMG0.png', 'img1.png', 'img2.png', 'IMG3.png', 'img10.png', 'img12.png']
- **
usort
— 使用用户自定义的比较函数对数组中的值进行排序**
// 说明:usort ( array &$array , callable $value_compare_func ) : bool
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
// 输出:[1, 2, 3, 5, 6]
2019/01/20
数组相关函数 No.5
- **
reset
— 将数组的内部指针指向第一个单元**
// 说明:reset ( array &$array ) : mixed
$array = array('step one', 'step two', 'step three', 'step four');
// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"
// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"
// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"
- **
list
— 把数组中的值赋给一组变量**
// 说明:list ( mixed $var1 [, mixed $... ] ) : array
$info = array('coffee', 'brown', 'caffeine');
// 列出所有变量
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// 列出他们的其中一个
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// 或者让我们跳到仅第三个
list( , , $power) = $info;
echo "I need $power!\n";
// list() 不能对字符串起作用
list($bar) = "abcde";
var_dump($bar); // NULL
- **
each
— 返回数组中当前的键/值对并将数组指针向前移动一步**
// 说明:each ( array &$array ) : array
// 返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为0,1,key和 value。单元 0 和 key 包含有数组单元的键名,1 和 value 包含有数据。
// 如果内部指针越过了数组的末端,则 each() 返回 FALSE。
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar); // [1 => "bob", "value" => "bob", 0 => 0, "key" => 0]
// 我们来看一下 list 与 each 和 reset 的连用
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
// 输出:["a" => "apple", "b" => "banana", "c" => "cranberry"]
- **
end
— 将数组的内部指针指向最后一个单元**
// 说明:end ( array &$array ) : mixed
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
- **
extract
— 从数组中将变量导入到当前的符号表**
// 说明:extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int
// 符号表是指当前php页面中,所有变量名称的集合
/**
* flag:第二个参数介绍
* EXTR_OVERWRITE:如果有冲突,覆盖已有的变量。
* EXTR_SKIP:如果有冲突,不覆盖已有的变量。
* EXTR_PREFIX_SAME:如果有冲突,在变量名前加上前缀 prefix。
* EXTR_PREFIX_ALL:给所有变量名加上前缀 prefix。
* EXTR_PREFIX_INVALID:仅在非法/数字的变量名前加上前缀 prefix。
* EXTR_IF_EXISTS:仅在当前符号表中已有同名变量时,覆盖它们的值。其它的都不处理。 举个例子,以下情况非常有用:定义一些有效变量,然后从 $_REQUEST 中仅导入这些已定义的变量。
* EXTR_PREFIX_IF_EXISTS:仅在当前符号表中已有同名变量时,建立附加了前缀的变量名,其它的都不处理。
* EXTR_REFS:将变量作为引用提取。这有力地表明了导入的变量仍然引用了 array 参数的值。可以单独使用这个标志或者在 flags 中用 OR 与其它任何标志结合使用。
*
* 如果没有指定 flags,则被假定为 EXTR_OVERWRITE。
*/
/* 假定 $var_array 是 wddx_deserialize 返回的数组*/
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n"; // 输出:blue, large, sphere, medium
2019/01/19
数组相关函数 No.4
- **
array_walk_recursive
— 对数组中的每个成员递归地应用用户函数**
// 说明:array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print'); // 输出:"a holds apple"、"b holds banana"、"sour holds lemon"
// 注意上例中的键 'sweet' 并没有显示出来。任何其值为 array 的键都不会被传递到回调函数中去。
- **
arsort
— 对数组进行逆向排序并保持索引关系**
// 说明:arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
// 输出:a = orange ;d = lemon;b = banana;c = apple
- **
asort
— 对数组进行排序并保持索引关系**
// 说明:asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
// 输出:c = apple;b = banana;d = lemon;a = orange
- **
compact
— 建立一个数组,包括变量名和它们的值**
// 说明:compact ( mixed $varname1 [, mixed $... ] ) : array
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city", "state");
$result = compact("event", "nothing_here", $location_vars);
print_r($result); // 输出:["event" => "SIGGRAPH", "city" => "San Francisco", "state" => "CA"]
- **
current
— 返回数组中的当前单元**
// 说明:current ( array &$array ) : mixed
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
$arr = array();
var_dump(current($arr)); // bool(false)
$arr = array(array());
var_dump(current($arr)); // array(0) { }
2019/01/18
- **
array_combine
— 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值**
// 说明:array_combine ( array $keys , array $values ) : array
// 两个数组数量如果不一致的情况是会出现警告的噢
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c); // 输出:['green' => 'avocado', 'red' => 'apple', 'yellow' => 'banana']
- **
array_count_values
— 统计数组中所有的值**
// 说明:array_count_values ( array $array ) : array
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array)); // 输出:[1 => 2, "hello" => 2, "world" => 1]
- **
array_diff_assoc
— 带索引检查计算数组的差集**
// 说明:array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) : array
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result); // 输出:["b" => "brown", "c" => "blue", 0 => "red"]
// 大家可以发现这里 red 有输出,为啥呢,因为第二个数组中 red 的 key 为 1。与数组一中的 key 为 0,不一致,所以有输出。
- **
array_diff_key
— 使用键名比较计算数组的差集**
// 说明:array_diff_key ( array $array1 , array $array2 [, array $... ] ) : array
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_key($array1, $array2)); // 输出:['red' => 2, 'purple' => 4]
- **
array_diff_uassoc
— 用用户提供的回调函数做索引检查来计算数组的差集**
// 说明:array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
function key_compare_func($a, $b)
{
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result); // 输出:["b" => "brown", "c" => "blue", 0 => "red"]
// 这个回掉函数有点没看明白啊 。。。。
2019/01/17
数组相关函数 No.2
- **
array_filter
— 用回调函数过滤数组中的单元**
// 说明:array_filter ( array $array [, callable $callback [, int $flag = 0 ]] ) : array
// 如果没有传递回掉函数,就起到过滤数组中空值的方法了
function odd($var)
{
// & 按位与
return($var & 1);
}
function even($var)
{
// returns whether the input integer is even
return(!($var & 1));
}
$array1 = array("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
print_r(array_filter($array1, "odd")); // 输出:["a" => 1, "c" => 3, "e" => 5]
print_r(array_filter($array2, "even")); // 输出:[6, 8, 10, 12]
- **
array_unshift
— 在数组开头插入一个或多个单元**
// 说明:array_unshift ( array &$array [, mixed $... ] ) : int
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue); // 输出:["apple", "raspberry", "orange", "banana"]
- **
array_shift
— 将数组开头的单元移出数组**
// 说明:array_shift ( array &$array ) : mixed
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack); // 输出:["banana", "apple", "raspberry"]
- **
array_pop
— 弹出数组最后一个单元(出栈)**
// 说明:array_pop ( array &$array ) : mixed
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack); // 输出:["orange", "banana", "apple"]
- **
array_push
— 将一个或多个单元压入数组的末尾(入栈)**
// 说明:array_push ( array &$array , mixed $value1 [, mixed $... ] ) : int
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack); // 输出:["orange", "banana", "apple", "raspberry"]
2019/01/16
- **
array_fill
— 用给定的值填充数组**
// 说明:array_fill ( int $start_index , int $num , mixed $value ) : array
// 如果 start_index 是负数, 那么返回的数组的第一个索引将会是 start_index ,而后面索引则从0开始
$a = array_fill(6, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a); // 输出:[6 => 'banana', 7 => 'banana', 8 => 'banana', 9 => 'banana', 10 => 'banana']
print_r($b); // 输出:[-2 => 'pear', 0 => 'pear', 1 => 'pear', 2 => 'pear']
- **
array_chunk
— 将一个数组分割成多个**
// 说明:array_chunk ( array $array , int $size [, bool $preserve_keys = false ] ) : array
// 第三个参数如果设为 TRUE,可以使 PHP 保留输入数组中原来的键名
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2)); // 输出:[['a','b'],['c','d'],['e']]
print_r(array_chunk($input_array, 2, true)); // 输出:[[1 => 'a',3 => 'b'],[5 => 'c',7 => 'd'],[9 => 'e']]
- **
array_slice
— 从数组中取出一段**
// 说明:array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] ) : array
// 第二个参数如果为负,则序列将从 array 中距离末端这么远的地方开始
// 第三个参数如果设为 TRUE,可以使 PHP 保留输入数组中原来的键名
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // [ "c", "d", "e"]
$output = array_slice($input, -2, 1); // ["d"]
$output = array_slice($input, 0, 3); // ["a", "b", "c"]
// note the differences in the array keys
print_r(array_slice($input, 2, -1)); // 输出:["c", "d"]
print_r(array_slice($input, 2, -2, true)); // 输出:[2 => "c"]
- **
array_diff
— 计算数组的差集**
// 说明:array_diff ( array $array1 , array $array2 [, array $... ] ) : array
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result); // 输出:[1 => "blue"]
- **
array_intersect
— 计算数组的交集**
// 说明:array_intersect ( array $array1 , array $array2 [, array $... ] ) : array
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result); // 输出:["a" => "green", "red"]
2019/01/15
- **
strip_tags
— 从字符串中去除 HTML 和 PHP 标记**
// 说明:strip_tags ( string $str [, string $allowable_tags ] ) : string
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text); // 输出:Test paragraph. Other text
// 允许 <p> 和 <a>
echo strip_tags($text, '<p><a>'); // 输出:<p>Test paragraph.</p> <a href="#fragment">Other text</a>
- **
explode
— 使用一个字符串分割另一个字符串**
// 说明:explode ( string $delimiter , string $string [, int $limit ] ) : array
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // 输出:piece1
echo $pieces[1]; // 输出:piece2
// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // 输出:foo
echo $pass; // 输出:*
- **
implode
— 将一个一维数组的值转化为字符串**
// 说明:implode ( string $glue , array $pieces ) : string
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(", ", $array);
echo $comma_separated; // 输出:lastname, email, phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // 输出:string(0) ""
- **
substr
— 返回字符串的子串**
// 说明:substr ( string $string , int $start [, int $length ] ) : string
$rest = substr("abcdef", -1); // 返回 "f"
$rest = substr("abcdef", -2); // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"
- **
str_word_count
— 返回字符串中单词的使用情况**
// 说明:str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) : mixed
/**
* format -> 指定函数的返回值,当前支持的值如下:
*
* 0 - 返回单词数量
* 1 - 返回一个包含 string 中全部单词的数组
* 2 - 返回关联数组。数组的键是单词在 string 中出现的数值位置,数组的值是这个单词
*
* charlist -> 附加的字符串列表,其中的字符将被视为单词的一部分
*/
$str = "Hello fri3nd, you're looking good today!";
print_r(str_word_count($str, 1)); // 输出:["Hello", "fri", "nd", "you're", "looking", "good", "today"]
print_r(str_word_count($str, 2)); // 输出:["Hello", "fri", "nd", "you're", "looking", "good", "today"]
print_r(str_word_count($str, 1, '3')); // 输出:[''Hello", "fri3nd", "you're", "looking", "good", "today"]
echo str_word_count($str); // 输出:7
2019/01/14
- **
abs
— 绝对值**
// 说明:abs ( mixed $number ) : number
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
- **
str_pad
— 使用另一个字符串填充字符串为指定长度**
// 说明:str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] ) : string
$input = "Alien";
echo str_pad($input, 10); // 输出 "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // 输出 "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // 输出 "__Alien___"
echo str_pad($input, 6, "___"); // 输出 "Alien_"
echo str_pad($input, 3, "*"); // 输出 "Alien"
- **
str_repeat
— 重复一个字符串**
// 说明:str_repeat ( string $input , int $multiplier ) : string
echo str_repeat("-=", 10); // 输出 "-=-=-=-=-=-=-=-=-=-="
- **
str_split
— 将字符串转换为数组**
// 说明:str_split ( string $string [, int $split_length = 1 ] ) : array
$str = "Hello";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1); // 输出:["H", "e", "l", "l", "o"]
print_r($arr2); // 输出:["Hel", "lo"]
- **
strrev
— 反转字符串**
// 说明:strrev ( string $string ) : string
echo strrev("Hello world!"); // 输出 "!dlrow olleH"
2019/01/13
- **
is_numeric
— 检测变量是否为数字或数字字符串 **
// 说明:is_numeric ( mixed $var ) : bool
- **
array_column
— 返回数组中指定的一列**
// 说明:array_column ( array $input , mixed $column_key [, mixed $index_key = null ] ) : array
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$first_names = array_column($records, 'first_name');
print_r($first_names);
// 输出:
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
// 输出:
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)
- **
array_search
— 在数组中搜索给定的值,如果成功则返回首个相应的键名 **
// 说明:array_search ( mixed $needle , array $haystack [, bool $strict = false ] ) : mixed
// 如果可选的第三个参数 strict 为 TRUE,则 array_search() 将在 haystack 中检查完全相同的元素。 这意味着同样严格比较 haystack 里 needle 的 类型,并且对象需是同一个实例。
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
$key = array_search('white', $array); // $key = false;
- **
in_array
— 检查数组中是否存在某个值 **
// 说明:in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
// 输出: Got Irix (in_array 区分大小写)
- **
array_unique
— 移除数组中重复的值 **
// 说明:array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
// 输出:
Array
(
[a] => green
[0] => red
[1] => blue
)
2019/01/12
- **
array_keys
— 返回数组中部分的或所有的键名 **
// 说明:array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] ) : array
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
// 输出:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)
- **
array_values
— 返回数组中所有的值**
// 说明:array_values ( array $array ) : array
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
// 输出:
Array
(
[0] => XL
[1] => gold
)
- **
array_merge
— 合并一个或多个数组 **
// 说明:array_merge ( array $array1 [, array $... ] ) : array
// 如果数组中有相同的字符串键名,则该键名后面的值覆盖前面的值;如果想让前面的值覆盖后面,则可以使用 + 号。
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
// 输出:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
- **
str_shuffle
— 随机打乱一个字符串 **
// 说明:str_shuffle ( string $str ) : string
$str = 'abcdef';
$shuffled = str_shuffle($str);
echo $shuffled; // 输出:bfdaec
- **
shuffle
— 打乱数组 **
// 说明:shuffle ( array &$array ) : bool
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
// 输出:7 8 11 1 17 3 14 2 16 15 5 9 4 18 12 20 13 10 19 6
2019/01/11
- **
iconv
— 字符串按要求的字符编码来转换 **
// 说明:iconv ( string $in_charset , string $out_charset , string $str ) : string
// 将字符串 str 从 in_charset 转换编码到 out_charset。
$text = "This is the Euro symbol '€'.";
echo 'Original : ', $text, PHP_EOL; // 输出:Original : This is the Euro symbol '€'.
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL; // 输出:TRANSLIT : This is the Euro symbol 'EUR'.
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL; // 输出:IGNORE : This is the Euro symbol ''.
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL; // 输出:Plain :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
- **
uniqid
— 生成一个唯一ID **
// 说明:uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] ) : string
// 获取一个带前缀、基于当前时间微秒数的唯一ID。
printf("uniqid(): %s\r\n", uniqid()); // 输出:uniqid(): 5c66c6e20fb7f
printf("uniqid('php_'): %s\r\n", uniqid('php_')); // 输出:uniqid('php_'): php_5c66c6e20fbde
printf("uniqid('', true): %s\r\n", uniqid('', true)); // 输出:uniqid('', true): 5c66c6e20fbe59.21437161
**
gettype
— 获取变量的类型 **Warning! 不要使用 gettype() 来测试某种类型,因为其返回的字符串在未来的版本中可能需要改变。此外,由于包含了字符串的比较,它的运行也是较慢的。
**
settype
— 设置变量的类型 **
// 说明:settype ( mixed &$var , string $type ) : bool
// 将变量 var 的类型设置成 type。
$foo = "5bar"; // string
$bar = true; // boolean
settype($foo, "integer"); // $foo 现在是 5 (integer)
settype($bar, "string"); // $bar 现在是 "1" (string)
- **
getcwd
— 取得当前工作目录 **
// 说明:getcwd ( void ) : string
// 取得当前工作目录
echo getcwd() . "\n"; // 输出类似:/home/didou
chdir('cvs');
echo getcwd() . "\n"; // 输出类似:/home/didou/cvs
2019/01/10
- **
strpos
— 查找字符串首次出现的位置 **
// 说明:strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
echo strpos("I love php, I love php too!","php"); // 输出:7
- **
stripos
— 查找字符串首次出现的位置(不区分大小写)**
// 说明:stripos ( string $haystack , string $needle [, int $offset = 0 ] ) : int
echo strpos("I love pHp, I love php too!","php"); // 输出:19
echo stripos("I love pHp, I love php too!","php"); // 输出:7
- **
strrpos
— 计算指定字符串在目标字符串中最后一次出现的位置 **
// 说明:strrpos ( string $haystack , string $needle [, int $offset = 0 ] ) : int
$foo = "0123456789a123456789b123456789c";
var_dump(strrpos($foo, '7', -5)); // 从尾部第 5 个位置开始查找
// 结果: int(17)
var_dump(strrpos($foo, '7', 20)); // 从第 20 个位置开始查找
// 结果: int(27)
var_dump(strrpos($foo, '7', 28)); // 结果: bool(false)
- **
strrchr
— 查找指定字符在字符串中的最后一次出现 **
说明:strrchr ( string $haystack , mixed $needle ) : string
echo strrchr("Hello world!","world"); // 输出:world!
- **
strstr
— 查找字符串的首次出现 **
// 说明:strstr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] ) : string
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 输出: @example.com
$user = strstr($email, '@', true); // 从 PHP 5.3.0 起
echo $user; // 输出: name
未完待续
其实我开始写文章的初心是对自己新学的知识点的一个总结,后面发现还有很多人看的,哈哈,挺开心的,每天上班的第一件事情就是看消息提醒,看到那么多的小红心,别提有多激动了,潜移默化的就促使自己学习更加的有激情,愿意写出更多更好的文章,哈哈。
昨天晚上我在记笔记的时候,偶然想到,为什么不放出来,让有需要的人可以一起进步呢,哈哈,就果断把笔记中记忆 PHP 函数的内容,就放到这里来了,哈哈。
大家如果有建议的 PHP 函数,可以放到评论区,我来更新学习哈。
本作品采用《CC 协议》,转载必须注明作者和本文链接
高认可度评论:
代码写得多了自然就记住了,刻意去记忘记的可能性很大。
@fatrbaby 因为发现自己用来用去的函数都是自己所熟悉的,复杂点的也是用自己熟悉的函数进行叠加处理,其实大部分都是有更好的函数替代,但是自己都不知道它的存在,记这些函数,其实也是混个脸熟,知道有这么个东西,以后有类似的需求了,再去查询具体的用法,这样也不会忘记的很快,哈哈
一起学习!
代码写得多了自然就记住了,刻意去记忘记的可能性很大。
我从来不记,都是百度现查
@fatrbaby 因为发现自己用来用去的函数都是自己所熟悉的,复杂点的也是用自己熟悉的函数进行叠加处理,其实大部分都是有更好的函数替代,但是自己都不知道它的存在,记这些函数,其实也是混个脸熟,知道有这么个东西,以后有类似的需求了,再去查询具体的用法,这样也不会忘记的很快,哈哈
可以尝试把 parms 和 return 附加上 :+1:
@afoolishman 好的,大佬 :relaxed:
@Echos :sunglasses: 菜鸟养成记,哈哈
坚持:star:
是我认识的那个超哥吗?
@xiaoguo0426 哈哈,是你认识的那个超哥 :laughing:
一起学习
楼主在超哥的云养牛公司工作?
很有感触,一起学习!
@houmuxu :blush::blush:
@select_and_action 不是的呢 :stuck_out_tongue_closed_eyes:
@lianglunzhong :bowtie:
@ly560020 :bowtie: 学习 :star:
可以按分类进行学习,比如数组、字符串、URL 、文件,数组和字符串的内置函数比较多,都是几十个:joy:
@Nick 好的 :relaxed:
弱弱问句,在哪家公司,哈哈哈
弱弱的问一下 左侧最下面的那个按照日期展示的列表是怎么做的
点击几日跳转到几日的内容节点??
我觉得可以去看看laravel框架源码中的PHP函数,这样可以结合源码来分析函数的使用。
@xiaobei 在腾讯呢,不过不是正式员工 :cry:
@hustnzj 好滴,谢谢大佬指点 :relaxed:
@传说中的五毛 那是自带的,哈哈,heading

哇哦,厉害,棒棒哒
感谢楼主的分享,个人觉得很受用。而且我把你的思路跟我最近练车的经验一比较大有裨益,不过对于这种方法记忆PHP函数个人觉得保持开发的流畅性是最重要的,但是用这种方法用来鞭策自己的学习习惯以及反思总结是非常值得肯定的,对于记忆PHP函数我个人觉得不用可以,可能我理解的有偏颇?
@满矅帆 哈哈,主要是我基础差,所以决定记一下函数的,每天花的时间也没多少。等常用的函数记得差不多了,就可以转移到其他的学习点了的。不过还是谢谢建议哈 :relaxed:
建议多写。刻意去记函数,很容易忘记。写多了,自然就记住。比如数组的很多函数都可以用foreach 实现。当你需要遍历的时候,你可以尝试换用数组的函数式写法。比如array_map.
@xianyunyehe 是呀,要多写。当想用 foreach 处理数据的时候看看有没有合适的函数替换,这个点好,哈哈
博主……介不介意我把你的代码翻成 Laravel Collection , 应该很好玩……还有,十万行代码,我一直按回车可以么……
@Shuyi 没事呀,翻吧。后面那句话就随意你了,反正敲代码是跟你积累,又不是别人 :relieved:
@Shuyi 一直回车, 你是挑逗博主的积极性么 ? 哈哈
好东西,点个赞
现在已经21号了 作者加油啊
要日更的节奏
php7增加了random-int
死记硬背是最无效的,有的函数有可能一辈子都不会用到,只有项目实践才会更加深刻
刚学习的时候能记住很多,后来基本都忘了
突然发现你坚持这么久了~~~
真的优秀
@james_xue 我觉得这不等于死记硬背,通过这种方式熟悉更多的 php 函数。Code 的时候效率更高,还能用上一些高级用法,和高阶函数。
如果你哪天断掉了 我会想 你那天肯定去陪妹子去了:smirk:
@Flourishing 哈哈,要是哪天碰不到电脑,可能就会断掉了
能坚持住真的不容易。加油。
大佬是手册里找的函数吗 还是其他什么渠道呢?
@JasonG 对呀,手册里面
能不能请你推荐一些学习的方法和资料 刚入门php,知识体系什么紊乱,不知道怎么去循序渐进的深入研究
优秀,已经突破了21天,成为了习惯,期待你这篇帖子到打不开的时候,这样就给站长一定的优化压力,哈哈。
加油
@深入浅出 已经在准备了哈
厉害了!,连过年都不放过啊,加油
记得我几年前学PHP 的时候是按照字母索引来学习的
加油,好多都忘了,一起学习
@imvkmark :blush:
@sunniness 前面更新的都忘记了,现在在回顾和练习,没有继续更新新的函数了,哈哈 :relaxed:
@Ciroy 已经打开很慢了,哈哈,要请站长来压压惊了。
配置太低吧
立一个flag,每天十个
PHP
函数的进度复习你上面列举的内容,希望尽快赶上你的进度 :see_no_evil: :see_no_evil:这里出错了!
@Flourishing 哈哈,已更正
:joy:我也是才刚开始学php 和laravel框架,也是觉得函数要多记才好,多多向学习楼主
造了一个速查表 https://free-andy.github.io/php-dict
@Wi1dcard 在github上看到你的百度小程序的项目了,很感谢
@free-andy 好用,谢谢
为豪哥疯狂打 call 。 :smile: