Skip to main content

Posts

Showing posts from March, 2013

Practising PHP ... the easy way

HTML and JavaScript are so easy to practise and experiment with because they are client side languages. All you need is a text editor and a web browser. Whereas PHP is a server-side language, meaning you need a server on which to host the code. Increasingly, however, it has become easier and easier to learn PHP without a complicated setup.


MAMP and WAMP have been around for quite a while now and are great packages for testing MySQL and PHP, but even easier to get started with is HyperEdit (OS X). And yes, it had to happen sooner or later, there is an app on the iPad for writing and testing PHP called Kodiak PHP.
There are other apps on OS X (and Windows) with the same functionality as HyperEdit, but none that I've found as easy to get started with and which cut through all the IDE fuss to be something that is quick and simple to use. Kodiak matches this ease of use, and is a dream for anyone who wants to code on the sofa in the evening.
Kodiak does require some cut and paste since…

Two ways to convert an array of any length into a string with "and" before final entry in PHP

First way is:

 <?php

function author_array($value) {

if (is_string($value)) $author=$value;

else if (is_array($value))
{
$i=0;
$array_length=count($value);
while ($i<$array_length) {

// Final author
if ($array_length-$i==1) $author=$author.$value[$i];
// Penultimate author
else if ($i==$array_length-2) $author=$author.$value[$i]." and ";
// All other entries
else $author=$author.$value[$i].", ";
$i++;
}

}
return $author;
}
echo author_array(array("Sam","Jim", "Jackie","Simon"));
?>
The alternative is to implode the array, and then use regular expressions and string search and replace functions (preg_replace and substr_replace)

<?php

// create an array
$array = array("Sam","Jim", "Jackie","Simon");
// implode the array so we have a string of names with commas inside
$comma_separated = implode(",", $array);

// make commas the search pattern
$pattern = '/(,)/'…