【问题标题】:php array, to check if a value at key is set or not and update accordinglyphp 数组,检查是否设置了键的值并相应更新
【发布时间】:2011-07-24 18:00:56
【问题描述】:

我初始化了一个名为 $present 的 php 数组,该数组的目的是如果名称存在则保存值 1,如果名称不存在则保存值为零。我有一个大小为 10 的名称数组。下面是提到的代码,但它不起作用。

$present = Array();
for($i=0;$i<=10;$i++){
    if(!isset($present[$name[$i]])) {
       $present[$name] = 1;
     }
     else echo $present[$name[$i]];
}

我也试过这个:

$present = Array();
    for($i=0;$i<=10;$i++){
        if(empty($present[$name[$i]])) {
           $present[$name] = 1;
         }
         else echo $present[$name[$i]];
    }

请帮忙谢谢!

【问题讨论】:

  • 你为什么先用$name[$i]然后$name
  • $present 在这些示例的开头是空的,应该是吗?什么是$names?我们可以使用所需的输入/输出

标签: php arrays boolean isset


【解决方案1】:

我不确定你到底想在这里做什么,但如果你只是想跟踪一个名字是否存在,你可以让 $present 成为一个名字数组,然后使用in_array.

$present = array('John', 'Paul', 'George');

echo in_array('John', $present);          # returns 1
echo in_array('MacArthur', $present);     #returns 0

【讨论】:

    【解决方案2】:

    我认为这可能是您正在寻找的。将 $i 设置为 1 时,您错过了它。

    $present = array();
    for($i=0;$i<=10;$i++){
        if(!isset($present[$name[$i]])) {
           $present[$name[$i]] = 1;
         }
         else echo $present[$name[$i]];
    }
    

    【讨论】:

    • 但是$present中没有设置元素他需要告诉我们更多
    【解决方案3】:

    应该是:

    $present = Array();
    for($i=0;$i<10;$i++){
      if(!isset($present[$name[$i]])) {
           $present[$name[$i]] = 1;
         }
         else echo $present[$name[$i]];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 2015-08-05
      • 2014-09-05
      • 1970-01-01
      相关资源
      最近更新 更多