2010-07-29 191 views
-1

的几个问题 “究竟是什么最短的代码?”:PHP代码优化

  1. 没有{}

    if($match->name == "Marry") { 
        $match = true; 
    } 
    
  2. 没有{}

    if($match->name == "Marry") { 
        $match = true; 
    } else { 
        $match = false; 
    } 
    
  3. 如何询问if $match = true

  4. 如何询问if array() has any value

  5. 如何询问if $variable has numeric value(0-9)?

  6. 如何询问if $variable's first symbol isn't a letter or number

  7. 如何询问if $match = false

+1

针对内存中字节码的最小大小进行优化?最快的执行?或开发人员输入的字符数最少? – 2010-07-29 16:14:09

+2

请让它被优化以便其他程序员在项目中简单理解。我需要解密一个__的时间,我可以在一行代码中做到这一点!'_废话并不好笑。再说一遍,我通常是在我以前的日子/年里把那条单行意大利面条放在那里的那个。为我服务的权利。 – Wrikken 2010-07-29 16:20:01

回答

1

1 )

$match = ($match->name == "Marry") ? true : $match; 

2)

$match = ($match->name == "Marry"); 

3)

if ($match === true) {} 

4)

$array = array(); 
if (!empty($array)) {} 

5)

if (is_numeric($variable)) {} 

6)

if (ctype_alnum($variable[0]))) {} 
2

1)

if($match->name == "Marry") { 
    $match = true; 
} 

这已经足够短,你不能没有伤害可读性(除了可能去掉括号改变它)。您正在使用相同的变量名

2)

$match = ($match->name == "Marry"); 

注意。

3)

if ($match = true) 

我想您if ($match == true),这应该只是if ($match)写入。

4)

EDIT我读此为 “具有任何(=一些)在特定值”,来检查是否数组为空可以使用empty

参见in_array

5)

有几种方式,一种可能的一种是

is_numeric($variable) && strlen("$variable") == 1 

要允许开始0,你可以做

is_numeric($variable) && $variable >= 0 && $variable <= 9 

6)

ctype_alnum($variable[0]) 
+0

1和2应该是'Withous {}'。 – hsz 2010-07-29 15:59:55

+0

@hsz我乞求你的赦免? – Artefacto 2010-07-29 16:05:48

+0

从技术上讲,您可以从由单行组成的if块中移除{}。但我不同意hsz。丢失它们会导致令人头痛的奇怪代码功能。 – 2010-07-29 16:16:27

0
1) OK 
2) $match = ($match->name == 'Marry'; 
3) if ($match) 
4) if (count($array)) 
5) preg_match('/^[+-]?\d+(\.\d+)?$/', $string) 
6) preg_match('/^[^0-9a-zA-Z]/', $string) 
1

A1。不能真的缩短,在第2部分的情况下接受

A2。 $ match =($ match-> name ==“Marry”);

A3。我怀疑你的意思是...

if ($match) { 
    echo "Value of $match evaluates as true"; 
} 

A4。不知道你的意思是...

if (empty($array)) { 
// or 
if (in_array($variable, $array)) { 

A5。

if (is_numeric($variable)) { 
    echo "it's numeric"; 
} 

A6。

if (preg_match('#^[^a-z\d]#i', $variable) { 
    echo "doesn't start with letter or number"; 
}