Chinaunix首页 | 论坛 | 博客
  • 博客访问: 575692
  • 博文数量: 207
  • 博客积分: 10128
  • 博客等级: 上将
  • 技术积分: 2440
  • 用 户 组: 普通用户
  • 注册时间: 2004-10-10 21:40
文章分类

全部博文(207)

文章存档

2009年(200)

2008年(7)

我的朋友

分类:

2009-04-05 20:06:31

PHP is a wonderful web programming language. Even though PHP has some very powerful features, it’s quite easy to get buried with the complex stuff that you may not be aware of some really cool PHP tricks. You can use these tricks to speed up your development quite a lot.

Short-Hand Echo

Normally:

  1. echo $variable; ?>  

Trick:

  1. $var?>  

Quickly Preview the Contents of an Array

Instead of using the foreach loop to echo the values, you can simply use the code below to preview the indexes and the values associated with each index of an array using the following function.

  1.   
  2. $array = array("Color" => "Blue""Legs" => 4, "PlayStation 3" => "WWE Smackdown VS Raw");   
  3.   
  4. echo '
    ';   
  5. print_r($array);   
  6. echo '';   
  7.   
  8. ?>  

Outputs:

  1. Array   
  2. (   
  3.     [Color] => Blue   
  4.     [Legs] => 4   
  5.     [PlayStation 3] => WWE Smackdown VS Raw   
  6. )  

Print Blocks of Texts

Instead of using the complicated concatenation to join strings, you can use this nifty block command to print your long string.

  1. $text = <<
  2.   
  3. This is awesome!

      
  4.   
  5. Indeed!

      
  6.   
  7. OPEN;   
  8.   
  9. echo $text;  

Force a Secure HTTP Connection

  1. if(!($HTTPS))   
  2. {   
  3.     header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);   
  4.     exit;   
  5. }  

Use Comma Instead of Concatenation

  1. $name = 'roosevelt';   
  2.   
  3. echo 'just testing '$name;  

Use isset to check limits, rather than strlen

isset is faster, than strlen ;)

  1. $name = "Jack";   
  2.   
  3. //Slow   
  4. if (strlen($name) < 10)   
  5.     echo "Not long enough!";   
  6.   
  7. //Faster   
  8. if(!isset($name{10}))   
  9.     echo "Not long enough!";  

Use isset to search in an Array

  1. $Items = array("Rock""Paper""Ball""Bat");   
  2.   
  3. //Slow   
  4. if (in_array('Bat'$Items))   
  5.     echo "Found!";   
  6.   
  7. $Items = array("Rock" => 0, "Paper" => 0, "Ball" => 0, "Bat" => 0);   
  8.   
  9. //Fast   
  10. if (isset($Items['Bat']))   
  11.     echo "Found!";  

Quickly Get Date

  1. $Today = getdate();   
  2. $Month = $Today ['month'];   
  3. $Day = $Today ['mday'];   
  4. $Year = $Today ['year'];  

Avoid Unnecessary Curley Braces (2nd Bracket)

  1. $test = true;   
  2.   
  3. //Not Good   
  4.   
  5. if($test)   
  6. {   
  7.     echo "Testing!";   
  8. }   
  9.   
  10. //Good   
  11.   
  12. if($test)   
  13.     echo "Testing!";  

 

阅读(666) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~