php 如果键不存在,则默认数组值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9555758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:07:02  来源:igfitidea点击:

Default array values if key doesn't exist?

phparraysdefault

提问by cgwebprojects

If I have an array full of information, is there any way I can a default for values to be returned if the key doesn't exist?

如果我有一个充满信息的数组,如果键不存在,有什么方法可以默认返回值?

function items() {
    return array(
        'one' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'two' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'three' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
    );
}

And in my code

在我的代码中

$items = items();
echo $items['one']['a']; // 1

But can I have a default value to be returned if I give a key that doesn't exist like,

但是,如果我提供一个不存在的密钥,我是否可以返回一个默认值,

$items = items();
echo $items['four']['a']; // DOESN'T EXIST RETURN DEFAULT OF 99

回答by Hein Andre Gr?nnestad

I know this is an old question, but my Google search for "php array default values" took me here, and I thought I would post the solution I was looking for, chances are it might help someone else.

我知道这是一个老问题,但是我在 Google 上搜索“php 数组默认值”把我带到了这里,我想我会发布我正在寻找的解决方案,它可能会帮助其他人。

I wanted an array with default option values that could be overridden by custom values. I ended up using array_merge.

我想要一个可以被自定义值覆盖的具有默认选项值的数组。我最终使用了array_merge

Example:

例子:

<?php
    $defaultOptions = array("color" => "red", "size" => 5, "text" => "Default text");
    $customOptions = array("color" => "blue", "text" => "Custom text");
    $options = array_merge($defaultOptions, $customOptions);
    print_r($options);
?>

Outputs:

输出:

Array
(
    [color] => blue
    [size] => 5
    [text] => Custom text
)

回答by Slavik Meltser

As of PHP 7, there is a new operator specifically designed for these cases, called Null Coalesce Operator.

从 PHP 7 开始,有一个专门为这些情况设计的新运算符,称为Null Coalesce Operator

So now you can do:

所以现在你可以这样做:

echo $items['four']['a'] ?? 99;

instead of

代替

echo isset($items['four']['a']) ? $items['four']['a'] : 99;

There is another way to do this prior the PHP 7:

在 PHP 7 之前还有另一种方法可以做到这一点:

function get(&$value, $default = null)
{
    return isset($value) ? $value : $default;
}

And the following will work without an issue:

以下将正常工作:

echo get($item['four']['a'], 99);
echo get($item['five'], ['a' => 1]);

But note, that using this way, calling an array property on a non-array value, will throw an error. E.g.

但请注意,使用这种方式对非数组值调用数组属性会引发错误。例如

echo get($item['one']['a']['b'], 99);
// Throws: PHP warning:  Cannot use a scalar value as an array on line 1

Also, there is a case where a fatal error will be thrown:

此外,还有一种情况会抛出致命错误:

$a = "a";
echo get($a[0], "b");
// Throws: PHP Fatal error:  Only variables can be passed by reference

At final, there is an ugly workaround, but works almost well (issues in some cases as described below):

最后,有一个丑陋的解决方法,但效果很好(在某些情况下会出现问题,如下所述):

function get($value, $default = null)
{
    return isset($value) ? $value : $default;
}
$a = [
    'a' => 'b',
    'b' => 2
];
echo get(@$a['a'], 'c');      // prints 'c'  -- OK
echo get(@$a['c'], 'd');      // prints 'd'  -- OK
echo get(@$a['a'][0], 'c');   // prints 'b'  -- OK (but also maybe wrong - it depends)
echo get(@$a['a'][1], 'c');   // prints NULL -- NOT OK
echo get(@$a['a']['f'], 'c'); // prints 'b'  -- NOT OK
echo get(@$a['c'], 'd');      // prints 'd'  -- OK
echo get(@$a['c']['a'], 'd'); // prints 'd'  -- OK
echo get(@$a['b'][0], 'c');   // prints 'c'  -- OK
echo get(@$a['b']['f'], 'c'); // prints 'c'  -- OK
echo get(@$b, 'c');           // prints 'c'  -- OK

回答by Mārti?? Briedis

This should do the trick:

这应该可以解决问题:

$value =  isset($items['four']['a']) ? $items['four']['a'] : 99;

A helper function would be useful, if you have to write these a lot:

如果你必须写很多这些,辅助函数会很有用:

function arr_get($array, $key, $default = null){
    return isset($array[$key]) ? $array[$key] : $default;
}

回答by Eric Keyte

As of PHP7.0you can use the null coalescing operator ??

从 PHP7.0 开始,您可以使用空合并运算符??

$value = $items['one']['two'] ?? 'defaut';

For <5.6

对于 <5.6

You could also do this:

你也可以这样做:

$value =  $items['four']['a'] ?: 99;

This equates to:

这相当于:

$value =  $items['four']['a'] ? $items['four']['a'] : 99;

It saves the need to wrap the whole statement into a function!

它省去了将整个语句包装成一个函数的需要!

Note that this does not return 99 if and only if the key 'a'is not set in items['four']. Instead, it returns 99 if and only if the value $items['four']['a']is false (either unset or a false value like 0).

请注意,当且仅当'a'未在 中设置密钥时,这不会返回 99 items['four']。相反,当且仅当值为$items['four']['a']false(未设置或类似 0 的 false 值)时,它才返回 99 。

回答by knittl

Not that I know of.

从来没听说过。

You'd have to check separately with isset

你必须单独检查 isset

echo isset($items['four']['a']) ? $items['four']['a'] : 99;

回答by Gerfried

The question is very old, but maybe my solution is still helpful. For projects where I need "if array_key_exists" very often, such as Json parsing, I have developed the following function:

这个问题很老了,但也许我的解决方案仍然有帮助。对于我经常需要“if array_key_exists”的项目,比如Json解析,我开发了如下函数:

function getArrayVal($arr, $path=null, $default=null) {
    if(is_null($path)) return $arr;
    $t=&$arr;
    foreach(explode('/', trim($path,'/')) As $p) {
        if(!array_key_exists($p,$t)) return $default;
        $t=&$t[$p];
    }
    return $t;
}

You can then simply "query" the array like:

然后,您可以简单地“查询”数组,例如:

$res = getArrayVal($myArray,'companies/128/address/street');

This is easier to read than the equivalent old fashioned way...

这比同等的老式方式更容易阅读......

$res = (isset($myArray['companies'][128]['address']['street']) ? $myArray['companies'][128]['address']['street'] : null);

回答by rostamiani

Use Array_Fill() function

使用 Array_Fill() 函数

http://php.net/manual/en/function.array-fill.php

http://php.net/manual/en/function.array-fill.php

$default = array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         );
$arr = Array_Fill(1,3,$default);
print_r($arr);

This is the result:

这是结果:

Array
(
    [1] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

    [2] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

    [3] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
            [d] => 4
        )

)

回答by Ihor Burlachenko

You can use DefaultArrayfrom Non-standard PHP library. You can create new DefaultArray from your items:

您可以使用来自Non-standard PHP library 的DefaultArray。您可以从您的项目创建新的 DefaultArray:

use function \nspl\ds\defaultarray;
$items = defaultarray(function() { return defaultarray(99); }, $items);

Or return DefaultArray from the items()function:

或者从items()函数返回 DefaultArray :

function items() {
    return defaultarray(function() { return defaultarray(99); }, array(
        'one' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'two' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
         'three' => array(
              'a' => 1,
              'b' => 2,
              'c' => 3,
              'd' => 4,
         ),
    ));
}

Note that we create nested default array with an anonymous function function() { return defaultarray(99); }. Otherwise, the same instance of default array object will be shared across all parent array fields.

请注意,我们使用匿名函数创建了嵌套的默认数组function() { return defaultarray(99); }。否则,默认数组对象的相同实例将在所有父数组字段之间共享。

回答by Ynhockey

I don't know of a way to do it precisely with the code you provided, but you could work around it with a function that accepts any number of arguments and returns the parameter you're looking for or the default.

我不知道如何使用您提供的代码精确地做到这一点,但是您可以使用一个接受任意数量参数并返回您正在寻找的参数或默认值的函数来解决它。

Usage:

用法:

echo arr_value($items, 'four', 'a');

or:

或者:

echo arr_value($items, 'four', 'a', '1', '5');

Function:

功能:

function arr_value($arr, $dimension1, $dimension2, ...)
{
    $default_value = 99;
    if (func_num_args() > 1)
    {
        $output = $arr;
        $args = func_gets_args();
        for($i = 1; $i < func_num_args(); $i++)
        {
            $outout = isset($output[$args[$i]]) ? $output[$args[$i]] : $default_value;
        }
    }
    else
    {
        return $default_value;
    }

    return $output;
}

回答by Nikolai R Kristiansen

In PHP7, as Slavik mentioned, you can use the null coalescing operator: ??

在 PHP7 中,正如 Slavik 所提到的,您可以使用空合并运算符: ??

Link to the PHP docs.

链接到PHP 文档