【问题标题】:PHP type check for associative array index isn't string, like it should be关联数组索引的 PHP 类型检查不是字符串,应该是
【发布时间】:2013-06-25 14:27:15
【问题描述】:

我在这里遇到了问题。

$arr = array ('1' => 'one');
var_dump(current(array_keys($arr)));
   // prints: int(1)
   // should print: string(1) "1"

我正在尝试创建一个关联数组,但 PHP 正在将我的字符串转换为我身上的整数。

我正在为一系列 按钮生成标记,并将选中的属性应用于其值与 POST 请求中的值匹配的那个,例如

$selected = isset($_POST[$this->name]) ? $_POST[$this->name] : null;
foreach ($this->options as $value => $label) {
   $html .= "<input type=\"radio\" name=\"{$this->name}\" value=\"$value\"".
            ($_POST[$this->name] === $value ? ' checked' : '').'>';
}

我可以只使用两个等号而不是类型比较;但是,如果数组是:

$this->options = array (
   '0' => 'No',
   '1' => 'Yes'
);

即使未设置 POST 值,它也会选择 0 选项。但是,它不应该选择任何单选按钮,因为它们都没有 null 值。

编辑:刚刚发现:“包含有效整数的字符串将被转换为整数类型。例如,键“8”实际上将存储在 8 之下。另一方面,“08”将不能强制转换,因为它不是有效的十进制整数。”在 PHP 手册中。认为有办法规避吗?

【问题讨论】:

  • 你也可以像(string)$integer那样输入转换为字符串
  • php 的类型很松散,如果它是字符串\int 则无关紧要
  • @Twisted1919:呃!谢谢,我不知道为什么我没有想到这一点,我是在处理错误的问题。
  • @Dagon:PHP 的松散类型实际上让我发疯了,我不希望 false、null 和 0 等值在它们意味着非常不同的事物时是等价的。
  • 那就别用php了,流行ruby和python

标签: php type-conversion associative-array


【解决方案1】:

正如@Twisted1919 所说,显而易见的解决方案是在检查中进行类型转换。

$selected = isset($_POST[$this->name]) ? $_POST[$this->name] : null;
foreach ($this->options as $value => $label) {
   $html .= "<input type=\"radio\" name=\"{$this->name}\" value=\"$value\"".
            ($selected === (string) $value ? ' checked' : '').'>';
}

谢谢!

【讨论】:

    【解决方案2】:

    这是不可能的。

    来自Manual

    A key may be either an integer or a string. If a key is the standard representation
    of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, 
    while "08" will be interpreted as "08").
    

    【讨论】:

    • 是的,我提到过。我一直在寻找替代解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多