2010-07-29 123 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"; 
}