Showing entries with tag "null".

Found 2 entries

Python: Null coallesce on an array

I have a small array in Python, and I need to get the 2nd element of that array, or a default value if it's not present. All the other languages (PHP, Perl, Javascript) I use have a simple null coallescing operator that makes it simple, but not Python. I got tired of writing it out every time to so I wrote a simple wrapper function:

x = [2,4,6]

# Get the 3rd item from x
y = arrayItem(2, x, -1) # 6
# Get the 8th (non-existent) item from x
y = arrayItem(7, x, -1) # -1
# Get an item from an array, or a default value if the array isn't big enough
def arrayItem(needle, haystack, default = None):
    if needle > (len(haystack) - 1):
        return default
    else:
        return haystack[needle]

If there is a better, simpler, built-in way I'm open to hearing it.

Leave A Reply - 1 Reply

PHP: Assign a default value to a variable

PHP E_ALL causes a warning to be thrown if you read an unitialized value from an array. For example if you did $debug = $_GET['debug']; but debug is not present in $_GET.

This function will conditionally assign a value to a variable that will not cause a warning to be thrown. It also has the added benefit of having a default option that you can specify.

function var_set(&$value, $default = null) {
    if (isset($value)) {
        return $value;
    } else {
        return $default;
    }
}

This allows us to safely assign a variable from the superglobals.

# Default of null if not in array
$debug = var_set($_GET['debug']);

# Specific default of 99
$level = var_set($_GET['level'],99);

Update: PHP 7+ has null coalesce built in which is better than this. $level = $_GET['level'] ?? 99

Leave A Reply