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

时间:2023-01-14 21:19:16

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

10 个解决方案

#1


61  

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.

我知道这是一个老问题,但是我在谷歌上搜索“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
)

#2


39  

As of PHP 7, there is a new operator especially for this case, called Null Coalesce Operator.

在PHP 7中,有一个新的操作符,特别是在这种情况下,叫做Null Coalesce操作符。

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

#3


19  

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;
}

#4


4  

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).

请注意,当且仅当项[' 4 ']中没有设置键'a'时,它不会返回99。相反,当且仅当$items[' 4 ']['a']的值为false时,它返回99(未设置或像0这样的假值)。

#5


2  

Not that I know of.

我不知道。

You'd have to check separately with isset

你必须和isset分开检查。

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

#6


2  

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
        )

)

#7


2  

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);

#8


0  

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;
}

#9


0  

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

您可以使用来自非标准PHP库的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.

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

#10


-1  

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

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

Link to the PHP docs.

链接到PHP文档。

#1


61  

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.

我知道这是一个老问题,但是我在谷歌上搜索“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
)

#2


39  

As of PHP 7, there is a new operator especially for this case, called Null Coalesce Operator.

在PHP 7中,有一个新的操作符,特别是在这种情况下,叫做Null Coalesce操作符。

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

#3


19  

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;
}

#4


4  

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).

请注意,当且仅当项[' 4 ']中没有设置键'a'时,它不会返回99。相反,当且仅当$items[' 4 ']['a']的值为false时,它返回99(未设置或像0这样的假值)。

#5


2  

Not that I know of.

我不知道。

You'd have to check separately with isset

你必须和isset分开检查。

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

#6


2  

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
        )

)

#7


2  

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);

#8


0  

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;
}

#9


0  

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

您可以使用来自非标准PHP库的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.

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

#10


-1  

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

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

Link to the PHP docs.

链接到PHP文档。