Geeks On PHP Episode 14

This week Stephen and I talk about user defined functions in PHP and why they matter. This is a precursor to our upcoming series on OOP in PHP.
Functions are the key to reusable code and thus should be used as often as it makes sense. Duplicating code is a big no no and should avoided at all costs, this is where functions come into play. Just last week I was working on a script that pulled back two different data sets (as arrays) and needed to do essentially the same thing to these two sets. Rather than duplicate the code twice I just converted my logic to a function and boom I was off an running with no duplication what-so-ever.
function fnXML_Body($adata)
{
$sxml_body = NULL;
$i = 0;
foreach($adata as $arow)
{
foreach($arow as $svar=>$sval)
{
switch($svar)
{
case "slabel":
$slabel = $sval;
break;
case "ivalue":
$ivalue = $sval;
break;
}
if($i < 2)
$sslice = "isSliced=\"1\"";
else
$sslice = NULL;
}
$sxml_body .= " \n";
$i++;
}
return $sxml_body;
}
Using the function above I can call pass a new data array to it as many times as I need to in a script without duplicating any code. The function accepts the data array, does some parsing and returns the XML that I need to generate a 3D Pie Chart.
The call to this function would be as follows:
$sxml_body = fnXML_Body($adata);
In the next couple weeks we are going to kick off a series on object oriented programming with PHP which will include all the basics as well as the tools needed to build a small web application from start to finish. We will be featuring a special guest for this series, it’s going to be very exciting and something you definitely don’t want to miss.
Follow both Stephen and Myself on Twitter and also subscribe via Tunes!
Enjoy the show and as always, stay geeky!
Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.
- Nicholas




