定义变量的多重条件 - PHP

时间:2014-06-09 10:03:04

标签: php if-statement

我有这个数组$node_actions

Array
(
    [new] => yes
    [fav] => no
    [eye] => no
    [edit] => yes
    [delete] => yes
)

有时会出现一些元素(比如neweye)。所以我需要定义一个具有此操作的变量:

$actions = $new.' '.$fav.' '.$eye.' '.$edit.' '.$delete;

我是这样做的:

if(!isset(($node_actions['new'])){
    $actions =$fav.' '.$eye.' '.$edit.' '.$delete;
}elseif(!isset(($node_actions['fav'])){
    $actions =$new.' '.$eye.' '.$edit.' '.$delete;
}elseif(!isset(($node_actions['eye'])){
    $actions =$new.' '.$fav.' '.$edit.' '.$delete;
}elseif(!isset(($node_actions['edit'])){
    $actions =$new.' '.$fav.' '.$eye.' '.$delete;
}elseif(!isset(($node_actions['delete'])){
    $actions =$new.' '.$fav.' '.$eye.' '.$edit;
}elseif(!isset(($node_actions['new']) && !isset(($node_actions['new']) ){
    $actions =$eye.' '.$edit.' '.$delete;
}else{

} //.... and so on

有一种优雅的简单方法吗?非常感谢。

3 个答案:

答案 0 :(得分:2)

尝试做:

$actions = "";
foreach($yourArr as $key => $val) {
  $actions .= $$key. " ";
}
$actions = trim($actions);

答案 1 :(得分:1)

尝试使用循环

foreach($arr as $k=>$v) {
  if(!empty($v)) {
    $actions .= $v.' ';  // yes no no yes yes 
    //$actions .= $k.' '; //new fav eye edit delete 
  }
}
echo $actions;

答案 2 :(得分:1)

我更喜欢这种方法         $ new = 1;     $ fav = 2;     $ eye = 4;     $ edit = 8;     $ delete = 16;是绑定到某个特定任务的变量,它们与来自GET或POST的某个变量(在本例中为$ action)相匹配

<?php

$new    = 1;
$fav    = 2;
$eye    = 4;
$edit   = 8;
$delete = 16;


$action = $fav | $eye; // OR $fav | $eye | $delete OR $new

if($action & $new) {
    echo "new";
} 

if($action & $fav) {
    echo "fav";
} 

if($action & $eye) {
    echo "eye";
} 

if($action & $edit) {
    echo "edit";
} 

if($action & $delete) {
    echo "delete";
} 

?>

希望这会对你有所帮助