I don’t really have a specific PHP problem that I’d like to expose in this thread. There are just a couple of patterns I keep on running and I’d like to improve my coding skills when it comes to them.
Could you help me make my code more efficient? And more “correctly indented?”
Hi, currently your examples are snippets so we are not able to see how these are used in their broader context.
Your examples 1 and 2 seem like they could be business logic. To this end a decent Pattern to look at is Parameterized Specification which is used to validate and select http://www.martinfowler.com/apsupp/spec.pdf Your third example is part of the SPL Iteratory PHP library and is very much depending in what situation you typically find yourself in when parsing and array - too little to go on hard to reduce this more minimalistically than it already is.
Hi ServerStorm. Thanks for your reply, I think you’re digging too deep. I’m just wondering if there would be a way to use the ternary operator, if while() should be used instead of foreach(). I’d like to know how to make those snippets look “more professional”. Just those snippets, not the whole architecture of an application.
‘Foreach loops’ are most appropriate for looping through arrays (like you show) or objects, ‘For loops’ are used for executing a block of code n number of times, and ‘While loops’ are best used when executing a block of code until a condition evaluates to true. So in your example you have chosen the best loop for arrays.
That is the last try I will do to help on this thread, cause if I got it wrong again it is ‘three strikes and I am am out’ “Batter Up!”
Regards,
Steve
if(isset($_GET[$var])) {
if(trim($_GET[$var]) == 'foor' and isset($otherVar)) {
//code
}
Bearing in mind your question is Isolated from any context, I can say that generally I’d prefer to get rid of the nested if(), and make it clear with formatting (and optionally, the extra parentheses as I have shown) that the condition is somewhat complex.
Using && instead of and also seems more implicit to me - and it in a visual scan of the code it cries out what it is doing.
That just makes more visual sense to me, and its much easier to add a 4th condition later (or indeed remove one) but that might just be me and I accept that not everyone will be in agreement.