Back

PHP Basics

Comments

<?php

// This comments out a single line

/*
This comments multiple lines
*/

?>

Echo

<?php

// Print out a string
echo "hello world";

?>
Output
hello world

Variables

<?php

// define a variable
$foo = "hello world";

// print the variable
echo $foo;

?>
Output
hello world

Functions

<?php

// define a function
function foo ( $bar )
{

	// return a string
	return "hello " . $bar;

}

echo foo ("world");
?>
Output
hello world

Arrays

<?php

// create an array
$foo = array(
	'ant',
	'bird',
	'dog'
);

// print the SECOND element
echo $foo[1];

?>
Output
bird

Associative Arrays

<?php

// create an associative array
$foo = array(
	'a'	=> 'ant',
	'b'	=> 'bird',
	'c'	=> 'cat',
	'd'	=> 'dog'
);

echo $foo['a'];

$foo['b'] = 'boy';

echo $foo['b'];

?>
Output
antboy

Multi-dimensional Arrays

<?php

$foo = array(
	'a'	=> array(
			array(
				'ant',
			),
			'apple'
		),
	'b'	=> 'bird',
	'c'	=> 'cat'
);

echo $foo['a'][0][0];

$foo['d'] = 'deer';

?>
Output
ant

Loops

For

<?php

for ($i = 0; $i<5;$i++)
{
	echo $i.',';
} 
?>
Output
0,1,2,3,4,

Foreach

<?php

$foo = array(
	'cat',
	'dog'
);

foreach ($foo as $bar)
{
	echo $bar.',';
}

?>
Output
cat,dog,

While

<?php

$count = 0;

while ($count < 5)
{
	echo $count.',';
	$count++;
}

?>
Output
0,1,2,3,4,

Debugging

print_r

<?php

$foo = array(
	'a'	=> array(
			array(
				'ant',
			),
			'apple'
		),
	'b'	=> 'bird',
	'c'	=> 'cat'
);

print_r($foo);

?>

Output

Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [0] => ant
                )

            [1] => apple
        )

    [b] => bird
    [c] => cat
)

try / catch

<?php

try {
	$d = 34 / 0;
}
catch (Exception $e) {
	echo $e->error();
}

?>

Output


Warning: Division by zero in /home/ddm11/public_html/php_basics.php on line 384

Include files

include("filename.php");

 

Back