In the tune of my answer to your question on check if variable isset and iterable, we can harness the power of null-coalescence to provide your code with default values.
$numbers = [ '4', '8', '15', '16', '23', '42' ];
if ( in_array( $some_obj->ID ?? 'duck', $numbers ) ) {
return true;
}
The above simply provides a default value that isn't going to be in your array. You don't have to use "duck", you can use uniqid()
or whatever other value that surely isn't found in the haystack.
Next, dealing with the expected but omitted boolean:
$new_obj = new stdObject(); // Forgetting to set property is_true
if ( $new_obj->is_true ?? false ) { // But I'd like notices here!
return true;
}
If object has no is_true
property, we default to false
, and this evaluates as if(false)
.
If you mute warnings, and more so, crank down error reporting, you'll be chasing bugs high and low down the road, when clear feedback is lost. Do this at the risk of your future sanity.
I'll throw in a bonus, seeing as your $numbers
array above is made of numeric strings. If you have declare(strict_types=1);
on, you'll get fatal errors when using "string-numbers" or "number-strings" for functions that expect int
or string
types. Examples:
<?php declare(strict_types=1);
$number = '4'; // "string-for-int"
$substring = substr('hello', 0, $number);
// : TypeError: substr(): Argument #3 ($length) must be of type ?int,
$substring = substr('hello', 0, (int) $number);
// : No problem
$string = 123; // "int-for-string"
$substring = substr($string, 0, 2);
// : TypeError: substr(): Argument #1 ($string) must be of type string, int given
$substring = substr((string) $string, 0, 2);
// : No problem
Using strict_types
is really quite helpful for ensuring that sloppy values doesn't simply get coerced into the types expected, transparently resulting in anomalous behavior.
If you're dealing with legacy code featuring strange data, strict types will teach you where things go wrong, and type-casting will help you patch things up after verifying that only values that can reasonably be coerced are being used.
To illustrate, you have deeper issues if you come across e.g. substr($str, 2, $end)
where $end = 'duck'
, given that (int) 'duck' === 0
. On the other hand, e.g. anything from a query string is, well, a string; but if e.g. you had a form UI submitting only basically valid numbers, you could reasonably typecast substr($str, 0, (int) $_GET['end'])
and deflect type errors.