Archive for the ‘PHP Tutorials’ Category

Convert array to string

Friday, October 19th, 2007

Problem: You want to convert an array to string so that it is easier to print the result instead of looping inside the array and have this printed

Old Solution:

$aArr = array("Have you ever seen",
"the beauty of the world.",
"The wonderful creation of the Lord." );
foreach($aArr as $sString) {
    print $sString;
}

Other Solution:

$aArr = array("Have you ever seen",
"the beauty of the world.",
"The wonderful creation of the Lord." );
$sString = implode(" ", $aArr);
print $sString;

In Action: I want to execute a linux command via PHP and get its result and extract the desire content. The example below will try to extract the ip address from the ifconfig command

exec("ifconfig", $aOutput);
$sTempString = implode(" ", $aOutput);
preg_match("/inet\saddr:(.*?)\s/i", $sTempString, $aMatch);
print $aMatch[1]; //

Determining if a number is odd or even

Thursday, October 18th, 2007

Problem: We wanted to determine if a number is even or odd

Notes: We know that even number end with 0, 2, 4, 6, 8 and odd numbers ends with 1, 3, 5, 7, 9. So how will we know if a number given is an even or odd number in a program..

Solution:

<?
$magic_number = 123568;
if($magic_number % 2 == 0) {
    print "The number is even.";
}  else {
    print "The number is odd.";
}
?>

Explanation: In the program above we use the modulus division. Modulus division unlike the ordinary division (/) returns the remainder instead of the quotient. So we tried modulo dividing the given number by 2 to determine if it is divisible by 2.

Swapping variables without using temporary variable

Thursday, October 11th, 2007

For example we wanted to swap two variable values given

$x = 10;
$y = 20;

The usual way of exchanging their variables is to use a temporary variable like the one below

$x = 10;
$y = 20;
$z = $x; // $z will be equal to 10 now which will serve as a temporary variable
$x = y; // $x will be equal to 20 now
$y = $z; // $y will be 10 now

Their is another way to do this without using temporary variable is the use of list() function

$x = 10;
$y = 20; 
list($x, $y) = array($y, $x);

You can also do this in multiple variables

$sDog1 = “Boston Terrier”;
$sDog2 = “American Bulldog”;
$sDog3 = “German Shepperd”;
$sDog4 = “Great Dane”;
list($sDog1, $sDog2, $sDog3, $sDog4) = array($sDog3, $sDog1, $sDog4, $sDog2); 

Getting a single character in a string

Tuesday, October 9th, 2007

This snippet of code will show how to get individual character from a string in a variable

$sMyName = “Darwin”;

print $sMyName[1]; // will print the letter “a”

How to use heredoc in PHP

Tuesday, October 9th, 2007

Heredoc also known as here-document is a way of specifying string literals or printing them literally without the use of quotes to threat them as literal strings. Heredoc preserves the line breaks and other whitespace (including indentation) in the text.

Heredocs start with <<< and a token or also known as delimiting identifier. The token or delimiting identifier don’t leading or trailing whitespace and followed by semicolon a to end the statement.

Example: We wanted to print this string

The quick brown fox
jumps over the lazy dog.
But what is the name of that dog 
whom the fox jumped over.

Usually we will use the print built in function of php and put line breaks to separate the lines

print “The quick brown fox \n”;
print “jumps over the lazy dog. \n”;
print “But what is the name of that dog \n”; 
print “whom the fox jumped over \n”;

In heredoc we literally print these sequence string without having to print all the lines 1 by 1;

Using heredoc

print <<< DOGS
The quick brown fox
jumps over the lazy dog.
But what is the name of that dog 
whom the fox jumped over.
DOGS; 

Heredocs in HTML

$sAnimal = “cat”;
$aZoo = array(”elephant”,”zebra”,”monkey”,”lion”,”bear”);
print <<< ZOO
There are different animals in the zoo.
It includes <b>$aZoo[1], $aZoo[3].</b>
There are also <font color=”red”>$sAnimal</font> here.
ZOO;

My PHP Coding Standard

Sunday, October 7th, 2007

Before I start writing my own PHP tutorials, I would to set the coding standards I will be following in the course of this tutorial. This aims to standardize all my snippets ( small chunk of code) in all examples I will be giving. I would like to emphasize that this is not a standard to all PHP programmers but just my personal preferences which we all do have.

Comments - - comments are piece of information that programmers usually put to their code to explain what it does. Comments are not actually part of the execution of a program but instead they are ignored by the PHP interpreter. It is a good practice in a programmer to put comments on his code because in the future, comments are the only guide a programmer can follow to understand a big pile of code. Comments may vary depending on what type comment to put.

1. single line comments - for single line commenting I use the double forward slash //

Example:

// this line will print your name
print "My name is Juan dela Cruz";

2. multi-line comment - for multi line I use /* and the closing */

Example:

/*
This is a multi-line comment
and goes all the way
up to this point
*/

Variables

for variables I use the camelize form. Meaning letters in my variable have combination of upper and lower case. But in addition I am affixing a single letter prefix that will determine the datatype of that variable. For example, if I would declare an array variable I would write $aMyArray.

Example:

$aMyArray = array(1,2,3,4); // contains array values
$sYourName = "Conai"; // contains string values
$iLoop = 100; // contains integer values
$oDBConnection = mysql_connect("localhost", "username", "password"); // object
$bIsTrue = false;  // boolean
$mMixedVariable = "test"; // mixed variable, a variable that may vary in datatype

For single usage or single letter variable there is an exemption on my rule.

for ($x=1; $x<count($aMyArray); $x++) {
    <statement here>
}

in the above example $x dont have any prefix on what datatype it is. I have sited this as my exemption.



Constants

as a rule constants should all be in uppercase and words separated by underscore(_)

Example:

define('HOST',  'localhost');
define('USER_NAME', 'root');
define('PASSWORD', '1234567a');



Conditional Statements

if statement

if ($x == 1) {
    <statement here after 4 solid spaces>
}

if - else statement

if ($x == null || $y != false) {
    <statement of if after 4 solid spaces>
} else {
    <statement of else after 4 solid spaces>
}

if -else if - else

if ($x > count($aResults)) {
    <statement of if after 4 solid spaces>
} else if ($x < count($aResults)) {
    <statement of else fif after 4 solid spaces>
} else {
    <statement of else after 4 solid spaces>
}

Loop statement

for loop

for($iCounter=0; $iCounter<10; $iCounter++) {
    <statement of for loop after 4 solid spaces>
}

while

while( !feof($oHandle) ) {
    <statement of while loop after 4 solid spaces>
}

do-while

do {
    <statement after 4 solid spaces>
}  while( $iLoop > 10) ;


Functions - function names are the same as the camelize form of my variables. Function names usually starts with small letters.

Example:

function checkThisVariable($mVariable) {
     if( is_integer($mVariable) ) {
        return "integer";
    } else if ( is_array($mVariable) ) {
        return "array";
    } else {
         return "undetermine";
    }
}

Class - class name are also in camelize form but the first letter is Capitalize to signify that it is a class when placed among other variables.

Example:

class Cabinet {
    var $sDrawer;
    function Cabinet () {
        $this->sDrawer = true;
    }
}