3 ms·
I've had trouble for a while now with chained ifs, as in: [CHUNK A] if (chunk a succeeds) { [CHUNK B] if (chunk b succeeds) { [CHUNK
by DanHulton 18y ago
I've had trouble for a while now with chained ifs, as in:
[CHUNK A]
if (chunk a succeeds) {
[CHUNK B]
if (chunk b succeeds) {
[CHUNK C]
if (chunk c succeeds) {
echo 'yay!'
}
else {
echo 'boo!';
}
}
else {
echo 'boo!';
}
}
else {
echo 'boo!';
}
This gets messy if there's anything interesting in those chunks. Instead, take advantage of short-circuiting and put those chunks in functions. Then you can rewrite the above as:
$success = do_chunk_a();
$success = $success && do_chunk_b();
$success = $success && do_chunk_c();
echo $success ? 'yay!' : 'boo!';
Also, use the ternary operator EVERYWHERE YOU CAN - you'll clean up so much code with it.
- nuclear_eclipse 18y agoeven better is: $success = do_chunk_a() && do_chunk_b() && do_chunk_c(); ...