truthiness and array values
Felix discusses the challenges of php errors, and language quirks and i applaud him for bringing questions like this to light because we may talk about solutions a lot, or how to do something, but we rarely talk about the smaller, often important way we think about a problem.
I thought I would chime in with my take on the matter, for whatever that’s worth. Imagine a scenario where you have an array of values, consider them boolean for the sake of argument. true or false, or at least they will evaluate to that.
he discusses a few different ways of avoiding those pesky php errors for missing array elements, and goes so far as to flirt with inline error suppression using the @ operator which is akin to slaughering your firstborn for kicks. or, feels that way at least.
I find whenever you have to really go against the grain and fight your data, or your language its usually a sign that I am looking at it wrong. There are cases, of course, when the language just fails. it cannot in a real way do what you need it to do without some magic, and php has lots of those issues. its an ugly language and barely expressive. that said, it works.
so back to our array then. his issue lies in this code:
if (isset($step['options']['merge']) && $step['options']['merge']) {
// do stuff
}
the thought process being you to avoid errors you have to check “pre-check” the value with the isset. While i’m not a huge fan of isset (or a number of php evaluations) and find them quirky at best, the line of code is essentially right. Whether concise or not is beyond the point.
my version is mostly the same:
if (array_key_exists('merge', $step['options']) && $step['options']['merge']) {
// do stuff
}
I like these collapsing conditionals. there is an explicitness (while verbose) to them that makes them valuable. And, when the array key fails the entire evaluation fails, skipping the possible error from running the second part of the condition.
better that than some external function as some suggest, and better that than supressing errors. Sometimes the confines of your language make your code a bit ugly, sometimes you must be verbose to be correct.
either way, i appreciate him writing out his thought process, and his possible solutions. We need more of that.
1 year ago