dongqun9403 2013-12-14 22:17
浏览 35
已采纳

从条件中删除关联数组中的特定键

I ran into a coding situation where i'd prefer to keep a certain condition as compact as possible:

// $data and $control are arrays
if($data==$control || ($someBool && $data==$control))
    return $c;

Of course this condition makes no sense that way. My goal is to remove a key from $control in the last part of my condition, before comparing it against $data.

Of course it could be done like this:

function chopByKey(array $arr, $key){
    if(!isset($arr[$key]))
        return $arr;
    unset($arr[$key]);
    return $arr;
}

And rewrite the condition:

if($data==$control || ($someBool && $data==chopByKey($control, 'someKey') ))
    return $c;

Please note

I am looking for a solution that i can use within my condition, not any solution that requires any additional step ahead of the condition or the definition of a custom function, be it anonymous or not.

My question is

Is there any more elegant way to do this, without defining a new custom function?

If yes, how?

  • 写回答

4条回答 默认 最新

  • douxian8883 2013-12-14 22:43
    关注

    I came up with the following line:

    $control = array('hello' => 'world', 'foo' => 'bar');
    $data = array('hello' => 'world');
    $someBool = true;
    
    if ($data == $control || $someBool && $data == array_diff_key($control, array('foo' => 0))) {
    

    Side effect is that $control is not modified by the condition.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100