PHP - 代码之间难以切换

时间:2011-08-05 03:09:03

标签: php switching

我有一个比这更大的代码的困境,但这大致是如此......

<?php
$other = 'white';

$array = array('red', 'blue', 'red', 'red',  'red');

foreach($array[1] as $match) //OR $match = $other;
{
    //Core Area
    if($match == 'red') { echo 'RED!'; }
    if($match == 'blue') { echo 'BLUE!'; }
    if($match == 'white') { echo 'white!'; }
}
?>

就像现在一样,$other 无法进入核心区域,而foreach不在其中。另一种方法是克隆 - 通过复制n'粘贴 - 到另一个地方。 ...哪个不能很好地工作......我已经尝试将该区域放在一个函数中,但是没有很多全局值,它似乎不是一个可行的选择。有没有办法在foreach=

之间切换

2 个答案:

答案 0 :(得分:1)

$array[] = $other;

现在$other位于数组中,因此它将位于您在循环中比较的内容列表中。

为什么你想要这个或你真正想要的东西飞过我的脑袋。

答案 1 :(得分:0)

<?php
$other = 'white';

$array = array('red', 'blue', 'red', 'red',  'red');

array_push($array, $other);    
foreach($array as $match) //OR $match = $other;
{ 
    //Core Area
  if($match == 'red') { echo 'RED!'; }
  if($match == 'blue') { echo 'BLUE!'; }
  if($match == 'white') { echo 'white!'; }
}

array_pop($array);

&GT;

可替换地:

<?php
$other = 'white';

$array = array('red', 'blue', 'red', 'red',  'red');

foreach($array as $match) //OR $match = $other;
{ 
    //Core Area
    custom_match($match);
}

custom_match($other);

function custom_match($color) {
  if($match == 'red') { echo 'RED!'; }
  if($match == 'blue') { echo 'BLUE!'; }
  if($match == 'white') { echo 'white!'; }
}
?>