PHP变量快捷方式?

时间:2017-09-14 02:42:55

标签: php variables

有没有更短的说法呢? 在我的标题中,我有这个:

$white1 = '/~jonathan/www/index.php';
$white2 = '/';
echo ($_SERVER['REQUEST_URI']); 

以下是我处理它的方式:

<?php 
if (
(($_SERVER['REQUEST_URI']) == $white1) 
or 
(($_SERVER['REQUEST_URI']) == $white2)
) 
echo 'custom-class'; 
?>

我还希望它有$white3$white4,允许?lang=en

3 个答案:

答案 0 :(得分:1)

您可以使用in_array执行此操作:

if (in_array($_SERVER['REQUEST_URI'], [$white1, $white2])) echo 'custom-class';

当然,您可以在之前定义匹配数组。

答案 1 :(得分:1)

将所有变量放入数组中并检查数组中是否有$_SERVER['REQUEST_URI']

<?php

$w = ['/~jonathan/www/index.php', '/'];
echo ($_SERVER['REQUEST_URI']);

if (in_array($_SERVER['REQUEST_URI'], $w))
    echo 'custom-class';

?>

答案 2 :(得分:1)

当我想要匹配的一些选项时,我喜欢像这样使用in_array

$options = array(
  '/',
  '/~jonathan/www/index.php',
);
if(in_array($_SERVER['REQUEST_URI'], $options)) {
  echo 'custom-class'
}

此方法可以轻松添加到$options列表,而无需更改有效负载或根据需要添加任何超过单个条目的内容。我喜欢保持数组的排序,使条目易于查找并保持清洁。

相关问题