Tuesday 30 April 2013

PHP: the first few tutorials, and getting to grips with a new (to me) language

G'day:
I'm back into the work swing of things now - having been remote for the last month - so have the usual 1h before work starts to knock out some blog bumpf. I'll not get this article finished in that time, but maybe at lunchtime. We'll see.

Anyway, a week or so ago I decided to start learning PHP, as you will know if you follow this blog with any sort of regularity. I promised to blog my progress, and it really seems like there hasn't been much yet. However I did dive in straight away and do some tutorials, I've just not had a chance (or motivation) to write anything about my findings yet.

But here I am now.


Right, so the first tutorials I landed on for PHP were at the Code Academy. I got put onto this outfit by my scrum master, who figured I could use some polish with my JavaScript during some downtime. I poopooed this notion initially, but after I learned something new on the very first round of JS tutorials, I decided to work through the rest. There's a mountain of stuff on the JS track, and I'm about a third of the way through them. Anyway, I was familiar with the site, and they've just added a PHP track, so I did all the PHP lessons. I did them all in one hit, and it probably only took a coupla hours to work through them. So not a bad primer.

What I'm gonna do here is review the code from the lessons, and comment on what I picked up. As with most of my PHP stuff at present, given I'm such a noob, it's not going to be earthshattering stuff. I make no apologies for this.

Control structures


First up, PHP has all the usual suspects for control structures: if / else / switch / for loops etc. Pleasingly / predictably (perhaps) the syntax is often the same as in CFML:

<?php
if (isset($_GET["location"])){
    if ($_GET["location"] == "here" ){
        echo "We're here";
    }elseif ($_GET["location"] == "there" ){
        echo "We're there";
    }else{
        echo "We're neither here nor there";
    }
} else{
    echo "Dunno what yer on about";
}
?>

(that's a really dumb example, I know)

<?php
if (isset($_GET["colour"])){
    switch ($_GET["colour"]){
        case "whero": 
        case "kura": {
            echo "red";
            break;
        }
        case "Kakariki": {
            echo "green";
            break;
        }
        case "kikorangi": 
            echo "blue";
        break;
        
        default: {
            echo "My Maori ain't that good";
        }
    }
} else{
    echo "Give me a colour";
}
?>

<?php
    $numbers = ["tahi", "rua", "toru", "wha"];
    
    for ($i=0; $i < sizeof($numbers); $i++){
        echo $numbers[$i] . "<br>";
    }
?>

Ignoring some of the variables stuff which I'll get to later, the control structures work the same way as in CFML, basically. NB: I know one would not usually use that sort of for() loop for looping over an array. I'm getting to that! Err... now...

Here's an alternative for looping over an array, using foreach, which is a much nicer way of going about things:

<?php
    $numbers = array("tahi", "rua", "toru", "wha");
    
    foreach ($numbers as $number){
        echo "$number<br>";
    }
?>

It also demonstrates alternate array-creation syntax. So there's both the literal syntax that CFML added in CF8, as well as using the array() function.

Oh yeah, and PHP arrays are zero-based.

Also note that one can just stick a variable into a string, and it will resolve OK:

echo "$number<br>";

That's cool, and also somewhat allays my annoyance that starting all variables with a $ makes the code look a bit crappy to my eyes. I prefer CFML's approach of having less rigorous variable naming, and then using # to identify it's a variable where it's ambiguous. But otherwise CFML doesn't require as much unnecessary clutter with its variable-naming, I think.

The alternative approach here would be to use the string concatenation operator, ".". Why the hell they picked a dot as a concatenation operator escapes me a bit - to me it's a fullstop (oh: a period if you must) so a "separation" sort of construct, not a joining one - but so be it:

echo $number . "<br>";

Back to control structures for a sec. For some reason which currently escapes me, PHP has two formats for doing control structure statements. There's the way that's familiar to us as per CFML, but there's also this version:

<?php
if (isset($_GET["colour"])):
    switch ($_GET["colour"]):
        case "whero": 
        case "kura": 
            echo "red";
        break;

        case "Kakariki":
            echo "green";
        break;

        case "kikorangi": 
            echo "blue";
        break;
        
        default:
            echo "My Maori ain't that good";
        break;
    endswitch;
else:
    echo "Give me a colour";
endif;
?>

Basically instead of the curly braces, one uses a colon at the top, and an endif / endswitch at the end. I googled around briefly for an explanation as to why they have two syntaxes, but didn't find a good one. There was a bit of subjective stuff around which syntax people prefer, but nothing on why there's two approaches in the first place. It does not seem like a very sensible feature to me (from my very newbie perspective).

Variables


Variables are loosely typed like they are in CFML:

<?php
    $x = 42;
    $y = 3.1415;
    $z = "one";
    
    echo "+ operator:<br>";
    echo $x + $y;
    echo "<br><br>";
    
    echo ". operator:<br>";
    echo $x . $y;
    echo "<br><br>";
    
    echo "+ operator with a string:<br>";
    echo $x + $z;
    echo "<br><br>";
    
    echo "both:<br>";
    echo $x + $y . "<br>";
?>

This yields:

+ operator:
45.1415

. operator:
423.1415

+ operator with a string:
42

both:
45.1415

Note how the + operator doesn't error when used with what's unambiguously a string, it just seems to treat the string as a null string or something. I'd prefer an exception here: garbage in/garbage out.

However one can also type cast values as well in PHP:

<?php
    $easierThanPi = (int) 3.1415; 

    echo $easierThanPi;
?>

Outputs:
3

That's quite handy, and is something I wished CFML had. Obviously it can be emulated by using various functions, but having the casting operator is a better approach.

Comments and semi-colons

Two unrelated things, but they are the last things covered in the first tranche of tutorials. Basically they're the same as in CFML.
As far as comments go, there's both the multi-line ones: /* [...] */, and the single-line ones: //.
There's also a variation in that # works the same way as //:


<?php
/*
echo "In a multi-line comment<br>";
*/

echo "Before a single line comment<br>"; // echo "After a single line comment<br>"; 
echo "Before a single line comment (alternate syntax)<br>"; # echo "After a single line comment (alternate syntax)<br>";
?>

Output:
Before a single line comment
Before a single line comment (alternate syntax)


And semi-colons are required... on all but the last line of a code block.


The next set of tutorials are on arrays, and you know what I'm like with arrays, so I'll probably bang on more than is appropriate for the second half of an article which is already over 1000 words. So I'll do that stuff separately.

This is a bit of a mess of an article, sorry, but it demonstrates the path I took in finding stuff out from the tutorials, and my investigations as to why things are they way they are.

And that's the end of lunchtime for me.

--
Adam