PHP小demo
1. compact 函数
$a = "123"; $b = "456"; $com = compact("a","b"); var_dump($com);
array(2) {
["a"]=>
string(3) "123"
["b"]=>
string(3) "456"
}
2. array_chunk 函数
<?php $count=10; while($count--) { $arr[]= $count; } $ret = array_chunk($arr, 4); print_r($ret);
Array
(
[0] => Array
(
[0] => 9
[1] => 8
[2] => 7
[3] => 6
)
[1] => Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
)
[2] => Array
(
[0] => 1
[1] => 0
)
)
3. date 函数
echo date("Ymd", time());
$str1 = ""; $str2 = 0;
$arr1 = array();
$arr2 = array(1,2,3);
echo $arr1 ? "Y" : "N";
echo $arr2 ? "Y" : "N";
echo null ? "Y" : "N"; echo empty($str1) ? "Y":"N"; echo empty($str2) ? "Y":"N";
NYNYY
echo "before exit "; exit; echo "after exit ";
before exit
6. array_shift 函数
7. array_pop 函数
8. json_encode 、json_decode函数
$json_data = array("status" => 0, "msg" => "账号错误"); $str = json_encode($json_data); echo $str;
注:json_encode过程中自动进行类型转换
9. for + &循环中改变变量
$arr = array( array("id" => 1, "name" => "A", "address" => "BJ"), array("id" => 1, "name" => "A", "address" => "BJ"), ); foreach($arr as &$k) { //这里使用&可以直接修改数组中的每个变量 $k["gender"] = "male"; } print_r($arr);
Array
(
[0] => Array
(
[id] => 1
[name] => A
[address] => BJ
[gender] => male
)
[1] => Array
(
[id] => 1
[name] => A
[address] => BJ
[gender] => male
)
)
10. 二维数组的转置
$user = array( 0 => array( "id" => 1, "name" => "张三", "email" => "zhangsan@sina.com", ), 1 => array( "id" => 2, "name" => "李四", "email" => "lisi@163.com", ), 2 => array( "id" => 5, "name" => "王五", "email" => "10000@qq.com", ), ); $ids = array_map("array_shift", $user); //注意array_map的用法 array_map("callback", array) var_dump($ids); //php5.4无array_column函数 //$names = array_column($user, "name"); $names = array_reduce($user, create_function("$v,$w", "$v[$w["id"]]=$w["name"];return $v;")); var_dump($names);
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(5)
}
array(3) {
[1]=>
string(6) "张三"
[2]=>
string(6) "李四"
[5]=>
string(6) "王五"
}
11. 函数调用
function add($a, $b) { //非类,不能用public等限定符修饰 return $a+$b; } echo add(1,2);
3
class A { function func() { echo get_class()." "; } } $obj = new A(); $obj->func();
class Base { protected function func1() { echo "Base func1 "; } public function func2() { echo "Base func2 "; } } class Sub extends Base{ } $obj = new Sub(); //$obj->func1(); // Call to protected method Base::func1() from context "" $obj->func2();
12. 字符串转整型、字符串比较
echo intval(10/3)." "; echo intval("1.2")." "; echo intval("0130Z110BF34")." "; $str = "0130Z110BF34"; if ($str != "000000") { echo "error "; }3
1
130
error
13. 接口的实现、类的继承
//默认不能自动加载其他文件的类、接口 interface IStu { //接口不能有变量 // public $var1 = "var1"; // public $var2 = "var2"; /*函数名不需要abstract修饰*/ function draw(); //接口不能有实现的函数 /* function learn() { echo "learning... "; } */ function write(); function pianno(); function chess(); } //这里不能有public修饰类,为什么? class Student { public $school = "china"; //不要使用如下形式,会发生嵌套初始化 // public function __construct($name = "good") { // $cls = Ucfirst($name)."Student"; // return new GoodStudent(); // return new $cls(); // } public static function getInstance($name) { $cls = Ucfirst($name)."Student"; return new $cls(); }
public function draw() { echo "draw something... "; } } //这里要加上abstract由于BJ没有实现所有的接口函数 abstract class BJ extends Student implements IStu { public $school = "bj"; public function chess() { echo "I chess in BJ "; } } class GoodStudent extends BJ { public function write() { echo "Hi, I am in ".$this->school." "; echo "good write "; } public function pianno() { echo "good pianno "; } } class BadStudent extends Student implements IStu{ public function write() { echo "bad write "; } public function pianno() { echo "bad pianno "; } public function chess() { echo "bad chess "; } }
//$obj = new Student("good"); //$obj = new GoodStudent(); $obj = Student::getInstance("good"); $obj->write(); $obj->chess();Hi, I am in bj
good write
I chess in BJ
interface IStu { //接口不能有变量 //public $var1 = "var1"; //public $var2 = "var2"; /*函数名不需要abstract修饰*/ function draw(); //接口不能有实现的函数 /* function learn() { echo "learning... "; } */ }
14. isset 函数
$arr = array( "TX" => array("TX-a" => "b", "TX-b" => "c"), "TY" => "c", ); var_dump(isset($arr["TX"]) && isset($arr["TX"]["TX-a"])); var_dump(isset($arr["TX"], $arr["TX"]["TX-a"])); //同上,更简洁 var_dump(isset($arr["TX"], $arr["TX"]["TX-c"])); var_dump(isset($arr["TZ"], $arr["TX"]["TX-c"])); var_dump(isset($arr["TZ"]));
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
15. mb_函数
$cardno = "3中—100901100322203"; echo substr($cardno, 0, 4) . "********" . substr($cardno, -4, 4)." "; echo mb_substr($cardno, 0, 4, "utf-8") . "********" . mb_substr($cardno, -4, 4)." ";
3中—1********2203
$str = "西安世纪JAVA编程思想设计模式之禅算法之道"; echo strlen($str)." ".strlen($str)." ". mb_strlen($str,"UTF-8")." "; //utf-8, utf8, UTF-8都可以? $str = mb_substr($str, 0, 19, "utf-8"); echo strlen($str)." ".strlen($str)." ". mb_strlen($str,"utf-8")." ";58 58 22
49 49 19
注:需要PHP中mbstring扩展的支持
16. simplexml_load_string 函数
$obj = @simplexml_load_string("abc"); //仅对xml格式的字符串进行解析,否则返回false var_dump($obj); $obj = @simplexml_load_string("<t>a</t>"); //注意解析出的每个元素是一个对象,对象里面是一个string var_dump($obj);
object(SimpleXMLElement)#1 (1) {
[0]=>
string(1) "a"
}
$xml = simplexml_load_string("<root><number>1</number></root>"); echo $xml->asXml(). " "; //自动加上xml头
<?xml version="1.0"?>
<root><number>1</number></root>
17. null比较
$ret = null;
echo $ret === false ? "false" : "not false";
echo "
";
echo $ret == false ? "false" : "not false";
$ret = null; echo $ret === false ? "false" : "not false"; //not false echo " "; echo $ret == false ? "false" : "not false"; //false
18. parse_ini_file 函数
$ini_path = "abc.ini"; $ini = parse_ini_file($ini_path); print_r($ini);
[first]
A = 1
B = 2
结果
Array
(
[A] => 1
[B] => 2
)
19. mysql-pdo进行数据库操作
$dsn = "mysql:host=localhost; dbname=test"; $username = "root"; $passwd = "doupei"; try { $dbx = new PDO($dsn, $username, $passwd); echo "Connected to db successfully!"." "; /* $sql = "select * from table_a where id = 2"; $res = $dbx->query($sql); foreach($res as $row) { print $row["id"]." "; print $row["name"]." "; } */ $name = "tom"; $id = 100; $sql = "insert into table_a(id, name) values(:id, :name)"; $stmt = $dbx->prepare($sql); $stmt->bindParam(":id", $id); $stmt->bindParam(":name", $name); $stmt->execute(); } catch (Exception $e) { echo "Faild to connect to db!"." "; echo $e->getMessage(); }
20. argv, argc变量
<?php print_r($argv); echo " $argc ";
命令行执行:php testPhpArgv.php a b c d
Array
(
[0] => testPhpArgv.php
[1] => a
[2] => b
[3] => c
[4] => d
)
5
21. 整数的判断
$arr = array(-1, -1.23, 0, 1, 2, 2.4, "12.0", "15"); foreach ($arr as $val) { //if (!preg_match("/^+?[1-9][0-9]*$/", $val)) { //整数的判断 if (!is_int(intval($val)) || intval($val) <= 0){ echo $val. "不是正整数"." "; } } $brr = array("-1", -1, "a1", "1a", "45", "1abc4", "-0.1111", "-0.12a"); foreach ($brr as $val) { //对应的整数值 echo $val . "对应整数 ". intval($val) . " "; }
-1不是正整数
-1.23不是正整数
0不是正整数
-1对应整数 -1
-1对应整数 -1
a1对应整数 0
1a对应整数 1
45对应整数 45
1abc4对应整数 1
-0.1111对应整数 0
-0.12a对应整数 0
22. static变量
class Student { public static $address = "bj"; public function __coustruct() { Student::$address = "sh"; } } $t = new Student(); echo Student::$address; //bj而不是sh
$arr = array(3=>"a",4=>"b",5=>"c",2=>"d",0=>"e"); foreach ($arr as $k => $v) { if ($k==3) { unset($arr[$k]); } } echo count($arr)." "; function filter($val) { return $val; } array_filter($arr, "filter"); echo count($arr)." "; unset($arr[2]); echo count($arr)." "; function odd($var) { // returns whether the input integer is odd 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); echo "Odd : "; print_r(array_filter($array1, "odd")); echo "Even: "; print_r(array_filter($array2, "even"));
4
4
3
Odd :
Array
(
[a] => 1
[c] => 3
[e] => 5
)
Even:
Array
(
[0] => 6
[2] => 8
[4] => 10
[6] => 12
)
24. 字符编码
$str = "AC,,,|BD1234_XXXzz"; //对应的UTF8、GBK编码相同 $reqstr = iconv("UTF-8", "GBK", $str); echo $reqstr." "; $reqstr = iconv("GBK", "UTF-8", $str); echo $reqstr." ";
AC,,,|BD1234_XXXzz
AC,,,|BD1234_XXXzz
25. array_merge 和 array的加法
$a = array(3 => "a", 4 => "b", 5 => "c"); $b = array(3 => "aa", 4 => "b"); $c = array_merge($a, $b); print_r($c); $d = $b + $a; print_r($d);
Array
(
[0] => a
[1] => b
[2] => c
[3] => aa
[4] => b
)
Array
(
[3] => aa
[4] => b
[5] => c
)
26. array_combine 等价于array_merge 再赋值
$arr = array("x2","x3","x3"); $arr[] = "xw5"; array_combine($arr,array(8,9)); print_r($arr);
PHP Warning: array_combine(): Both parameters should have an equal number of elements x.php on line 4
Array
(
[0] => x2
[1] => x3
[2] => x3
[3] => xw5
)
27. array_slice 函数
$arr = array("A"=>1, "B"=>2, "C"=>3); $sub = array_slice($arr, 0, 2); var_dump($sub);array(2) {
["A"]=>
int(1)
["B"]=>
int(2)
}
28. array_unique 函数
$arr = array("a","a","c","d"); $brr = array_unique($arr); print_r($arr); //$arr本身未变化 print_r($brr);
Array
(
[0] => a
[1] => a
[2] => c
[3] => d
)
Array
(
[0] => a
[2] => c
[3] => d
)