PHP Function & Arrays
PHP Function & Arrays
FUNCTION
A function is a set of program statements that
perform a specific task, and that can be called, or
executed, from anywhere in your program.
Syntax
function function_name(arg1,arg2...argN){
block of statements;
return;
}
CALLING FUNCTIONS
Syntax
functionName()
functionName( argument )
functionName( argument1, argument2 )
EXAMPLE
function add_footer() {
echo "<img src=\" footer_logo.jpg\" width=\"100%\"
height=\"7\">";
echo "Pangasinan State University<br/>";
echo "<br/>Mc Arthur Highway";
echo "<br />Urdaneta City";
echo "<p>or send questions to";
echo "<a href=mailto:info@psu.edu.ph> webmaster</a><br/>";
echo "<img src=\"footer_logo.jpg\" width=\"100%\" height=\"7\">";
return;
}
add_footer()
function describeMyDog() {
$color = "brown";
echo "My dog is $color <br/> ";
}
$color = "black";
describeMyDog();
echo "My cat is $color <br/>";
GLOBAL
function studentName() {
global $studName;
$studFname = "Ghen";
$studLname = "Lomibao";
$studName=$studLname.", ".$studFname;
}
studentName();
echo $studName;
ARRAY
ANATOMY OF AN ARRAY
Array
An array stores a group of values in a series of
elements under a single variable name. It elements are
represented by a maps keys (or indexes) to values.
Three Types of Arrays
Indexed arrays
Associative arrays
Multidimensional arrays
CREATING ARRAYS
Example1
$authors = array("Steinbeck", "Kafka", "Tolkien", "Dickens" );
Example
$hayop['A'] = "pusa";
$hayop['B'] = "aso";
$hayop['C'] = "baka";
Example3
$hayop[] = "pusa";
$hayop[] = "aso";
$hayop[] = "baka";
Example4
$myBook = array("title" = > "The Grapes of Wrath", "author" = > "John
Steinbeck", "pubYear" = > 1939 );
ACCESSING ARRAY ELEMENTS
Example1
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”,
“Dickens” );
$myAuthor = $authors[0];
$anotherAuthor = $authors[1];
Example2
$myBook = array("title" = > "The Grapes of Wrath", "author"
= > "John Steinbeck", "pubYear" = > 1939 );
$myTitle = $myBook["title"];
$myAuthor = $myBook["author"];
LOOPING THROUGH ARRAYS
echo $comma_separated;
ARRAY FUNCTIONS
explode
Split a string by string
Returns an array of strings
Example
$string = 'lastname, email, phone';
$array = explode(",", $string);
print_r($array);
REFERENCES
php.net
tutorialrepublic.com/php-tutorial
Tutorialspoint.com/php/index.html
w3schools.com/php