简体   繁体   中英

Set array value to nothing in php

I try to set an array to nothing but it does not work (which is kind of expected).

$array = [
    'some_key' => my_function()

     /* 30 more rows of values */
];

function my_function() {
    return null;
}

print_r($array);

The above will display:

Array(
    'some_key' =>
)

The result I want is in this case an empty array item, because the function return a null value.

The alternative is a bit more ugly:

$some_key = my_function();

$array = [
     /* 30 more rows of values */
];

if(isset($some_key)) {
    $array['some_key] = $some_key;
}

function my_function() {
    return null;
}

print_r($array);

The reason I don't like this approach is that I need to step away from my array tree and add the values in later.

It's easier to see in a large array like this one:

This is my output but the input looks similar.

[component] => Array
    (
        [id] => my-snippet
        [raw] => my-snippet
        [view] => preview
        [template] => tool
        [type] => snippet
        [ctype] => text/html
        [url] => 
    )

To add functions or variables to this array tree looks great. Storing the array in a variable and then add the variables later is not as readale. Is it possible to solve?

@mlask gave the solution in a comment. To use array_filter is a way to solve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM