Tuesday, April 20, 2010

Workshop 4 PHP Functions & Arrays

FUNCTIONS

Functions are blocks of code that you can call from the main program. 

<?php

function print2lines() {
    echo "This is line 1", "<br>";
    echo "This is line 2", "<br>";
}
print2lines();
?>


You can also pass arguments into a function

<?php

function printlines($txt) {
    echo  " $txt <br>";
}
printlines("This is line 1");
printlines("This is line 2");
printlines("This is line 3");
?>

You can also get the function to return an argument

<?php

function addnums ($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}
echo addnums(5,9);
// print 14 

?> 


Variables declared in a function remains only in the function. You can however use global variables should you wish to use variables within a function.

<?php

$value = 100;

function currentmoney() {
    global $value;
    echo " I currently have RM $value <br>";
}
currentmoney();
?> 


ARRAYS

Creating arrays

In order to create an array, you would need to you the array function:

$lecturers = array("Yann", "Sam", "Ven Yu", "Tony", "Anitha");


You can also do this as well

$lecturers[] = "Yann" ;
$lecturers[] = "Sam";
$lecturers[] = "Ven Yu";
$lecturers[] = "Tony";
$lecturers[] = "Anitha";


Both will create an array called lecturers with 5 elements. By default the first element starts at position 0.

<?php
$lecturers = array("Yann", "Sam", "Ven Yu", "Tony", "Anitha");
echo $lecturers(1) ; // This will print Sams name
?> 


Associative Arrays

Instead of using numbers, you can also use named keys to number the arrays instead as illustrated in the following example.

$lecturers = array (
    "name" => "Yann",
    "dept" => "VIGIM",
    "subjects" => "ITC382"
    );

If you write

Echo $lecturers['dept']; // this will return VIGIM 


You can also make additions to an already existing associative array.

$lecturers['interests'] = "Video Games"; 



Multidimensional Arrays

A Multidimensional Arrays holds arrays of an array.

<?php

$lecturers = array (
        array (
"name" => "Yann",
            "dept" => "VIGIM",
            "subjects" => "ITC382"
            ),
array (
"name" => "Sam",
            "dept" => "VIGIM",
            "subjects" => "ITC211"
 ),
array (
"name" => "Tony",
            "dept" => "MT",
            "subjects" => "ITC123"
              ),
    );

    echo $character[1]['subjects']; // this will print out ITC211

?> 

0 comments:

Post a Comment