批改状态:合格
老师批语:少了总结 , 下次注意
<?php//声明一个函数:打印欢迎内容function hello(){echo '<h2 style=" color :lightblue">欢迎您!</h2>';}//调用函数hello();
<?php$phone_number = '13535645687';//strlen()函数,获取字符串长度if(strlen($phone_number)===11):echo '手机号正确';else: echo '手机号不正确';endif;////输出结果:手机号正确//substr()函数,截取字符串echo '该手机号的号段是:'.substr($phone_number,0,3);//输出结果:135//count():统计数组的元素个数echo count([1,2,3,'php','']);//输出结果:5
<?php//可变函数$function_name = 'setName';//声明一个为名称添加后缀的函数function setName(string $name):string{return $name.'_php.cn';}echo $function_name('首页');//打印结果:首页_php.cn
use关键字,可以在匿名函数中访问父作用域中的变量
<?php$arr = [0=>'admin',1=>'guest',12=>'wang',23=>'li'];$username=function (int $key) use($arr):string{return trim($arr[$key]) ;};echo $username(1);//输出结果:guest
<?php//1.字符串拼接//隐藏部分卡号function hide(int $cardno):string{$bin = substr($cardno,0,6);$last_four = substr($cardno,-4,4);return $bin.'****'.$last_four;}echo hide('6228481254654584');//输出结果:622848****4584//2.数组//找出数组中大于20的数$arr=[12,56,25,1,0,25];function seek(array $arr) :array {$res = array();foreach($arr as $value){if($value>=20){$res[]=$value;}}return $res;}printf('<pre>%s</pre>',print_r(seek($arr),true));//输出结果:// Array// (// [0] => 56// [1] => 25// [2] => 25// )//3.json//将字符串转换为json字符串function getList(string $list):string{$arr = explode(',',$list);return json_encode($arr);}echo getList('php,java,python,javascript');//输出结果:["php","java","python","javascript"]//4.序列化function err(string $eror_message):string{return serialize(['code'=>'110','message'=>$eror_message]);}echo err('未知错误');//输出结果:a:2:{s:4:"code";s:3:"110";s:7:"message";s:12:"未知错误";}//反序列化:unserialize()print_r(unserialize(err('未知错误')));//输出结果:Array ( [code] => 110 [message] => 未知错误 )
&可以引用传递
$a = $b=10;function sum($c,&$d){$c+=10;$d+=10;return $c.';'.$d;}echo sum($a,$b),'<br>';echo $a.';'.$b;//输出结果:// 20;20// 10;20//第一个参数为值传递:原变量值未改变;第二个参数为引用传递,值发生了改变
<?php//拼接查询语句//$order=''参数默认为空,可选function sqlStr($table,$fields,$where,$order=''){return 'select '.$fields.' from '.$table.' where '.$where.' '.$order;}//传4个参数echo sqlStr('`user`','`id`,`name`,`status`,`create_time`','`create_time`>1585850756','order by `create_time` desc');echo '<br>';//传三个参数echo sqlStr('`user`','`id`,`name`,`status`,`create_time`','`create_time`>1585850756');//输出结果://select `id`,`name`,`status`,`create_time` from `user` where `create_time`>1585850756 order by `create_time` desc//select `id`,`name`,`status`,`create_time` from `user` where `create_time`>1585850756
...数组名将所有参数放到一个数组中调用函数时也可以通过...数组名将数组的元素展开作为参数传递
例:
<?php//清除多个参数的值的空格function format(...$param){$res = array();foreach($param as $value){$res[]=trim($value);}return $res;}$arr = [' jack','r12546 '];print_r(format(...$arr));//输出结果:Array ( [0] => jack [1] => r12546 )
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号