Decisions

Introduction

My last three posts have been about learning PHP, so this month I thought I’d continue on a smaller scale. Given the current situation and the lack of decisions we have about our lives, I thought about the ‘switch’ statement that can be used as a cleaner way of implementing branching when you have many choices.

If you’ve not read my posts on the ‘The first step’ then they are: one, two and three, then they will help, especially part one to have the environment upon which to run the code presented here.

Other names / logos can be trademarks of their respective owners. Please review their website for details.

I am independent from the organisations listed above and am in no way writing for or endorsed by them.

All example ‘code’ presented is written by myself, please feel free to copy for educational purposes only.

If it does not work

If something goes wrong, then you need to look in the error log file. On the Pi, this will be located in the ‘/var/log/apache2’ folder as ‘error.log’ and you can use the command ‘tail’ to see the most recent events as the file is appended to. In other systems, hunt around for ‘error.log’.

Making a decision

Perhaps the most key thing about a modern logical computer is its ability to make decisions based on data. Those decisions are logical and reduce down from the complex to a simple ‘yes’ or ‘no’. From my understanding this has its roots with Alan Turing and is proof “On Computable Numbers, with an Application to the Entscheidungsproblem.” (en.wikipedia.org/wiki/Turing%27s_proof), which whilst I understand computer architecture and software engineering, the mathematics is beyond me.

The code

Please note: Only run this on a local server with no access from the outside world as there is no validation undertaken on the input, this is a ‘security’ risk.

Firstly the ‘switch’ version:

which when run on the web server gives:

and:

You can see that the statement is good at comparing values of the same thing, now if we look at the ‘if’ statement version:

you can see that it is functionally the same, however it could be considered less readable. But if you’re not looking at the same thing, then it is more flexible.

Conclusion

The basic language constructs such as ‘if’ and ‘switch’ are fundamental in automating the decision making process when turning tasks from a human to a computer driven one and form the basis of software.