Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
PHP
Hello everybody, I will be continuing the PHP section picking up from the previous author and from the point you have stopped in the April issue. In the last article, you have covered PHP comments, constants, variables and data types. Today we will be discussing more about nature of data types.
Data Types – continued...
Earlier we discussed four PHP’s simple data types – integer, string, float and boolean. If you recall the kind of data we stored in each type, all of them were capable of handling a single value. These are also known as scalar variables. There are two more important complex data types to be discussed – array, object.
Type Casting
I would like to explain one more concept related to data types before we jump in to arrays.
If you have worked with other programming languages such as C, you must have noticed that a variable can hold only a single type of data and the data type must be declared at the definition. In contrast, as we discussed in previous article PHP determines the data type of a variable depending on the value assigned to it. i.e PHP is a weakly typed language. Additionally, it can change the data type during the script execution time by assigning a value from another data type. Take a look at the following piece of code:
<?php $total = 530; // variable total is integer type $average = 78.4; // variable average is double type $total = "not available"; // PHP automatically identifies and changes data type of total to string ?>
Yeah, I know that sounds smart! There can be situations where we need to decide the data type we want to use on a variable rather than letting PHP decide it. This can be important when you want to perform some action related to a variable but you’re not allowed to do so because the variable is not in the expected data type. We use the term Type Casting to explain the concept of user explicitly defining desired data type.
<?php $marks = "67"; $average = (int)$marks; var_dump($average); //int(67) ?>
In above example, what’s important to note is the second line. There we have asked PHP to take value of $marks, interpret it as an integer (which is a string in definition) and store it in $average. Therefore, $average is set to be a variable of integer type. If you wish to see a list of possible casting types browse http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting.
I’m sure you might be wondering the purpose of var_dump() function. It is used in this example to print the information about variable $average; the data type and the value. So while you’re playing around with variables, try using var_dump() to find out how exactly PHP interprets your variable data types.
Arrays
An array in general programming is a variable that stores a set or a sequence of values. In other words, just as a scalar variable is a named location to store a single value, an array is a named location to store a group of interrelated values.
One array can have multiple elements, where each element can store a simple textual/numerical value or another array. An array that holds more arrays is known as a multidimensional array. These can be used to define complex data structures to cater various programming needs which we will come across later.
Let’s see how we define a variable to hold a simple array in PHP:
<?php $fruits = array("Orange", "Banana", "Mango", "Apple", "Guava"); ?>
As you can see we have now created a new named location (variable) $fruits to handle a group of elements by passing them all to array() function. Creating an array allows you to perform various useful actions with it such as using loop constructs to access each element in an array, sort an array alphabetically, transfer the values to a different page as a set etc. In general, arrays are useful to hold interrelated data in your code, load the content of a text file, load a record from a database table etc.
Each element or value stored in an array has an associated index (also called a key), which is helpful to access the element. To access a particular element, use the key within a pair of square brackets right after the array name. Note that PHP array indexes start from zero.
<?php $fruits = array("Orange", "Banana", "Mango", "Apple", "Guava"); echo $fruits[0]; // prints out Orange to the browser $fruits[3] = "Pineapple"; // Overwrite value Apple echo $fruits[2]; // prints out Mango to the browser echo $fruits[3]; // prints out Pineapple to the browser ?>
In most programming languages, you can find numerically indexed arrays. So you might be familiar with them if you have done some programming.
PHP also supports another useful type which is associative arrays. The difference is that they can have almost any type of array keys (typically strings) rather than plain numerical values.
<?php $products = array("Laptop" => 150000, "Mobile Phone" => 43000, "Webcam" => 5000); echo $products["Webcam"]; //prints out 5000 to the browser ?>
Above example illustrates how an associative array is defined where product names are array keys and related prices are array values.
Unlike in some other programming languages, in PHP we do not have to know the length/size of the array at its creation time. PHP arrays can grow during the execution time as we add new elements.
<?php $products["Flash Drive"] = 2000; // Adds new element to products array ?>
Just as we discussed earlier in the definition, an array element does not necessarily have to store a single value. It can hold another array as well (a set of sets). This is how we can create a two-dimensional array:
<?php $products = array( array("code"=>"P001", "name"=>"Laptop", "price"=>150000), array("code"=>"P002", "name"=>"Mobile Phone", "price"=>43000), array("code"=>"P003", "name"=>"Webcam", "price"=>5000) ); ?>
You can think of a two-dimensional array as a grid/table having rows and columns.
|
code |
Name |
price |
|
P001 |
Laptop |
150000 |
|
P002 |
Mobile Phone |
43000 |
|
P003 |
Webcam |
5000 |
If you recall the way we accessed one-dimensional fruits array in a previous example – we used name of the array and respective index. Here too it’s similar, except we need to have two indexes to identify an element. The first index represents the key of main array while second index represents the key of sub array we intend to access.
<?php echo $products[0]["name"]; // prints out Laptop echo $products[2]["price"]; // prints out 5000 echo $products[1]["code"]; // prints out P002 ?>
What we tested right now is how to store and retrieve values of a two-dimensional array. You do not have to stop from here. You can have any number of arrays inside the arrays and have multidimensional arrays following the same concept. I will leave that part for your interest!
I hope you have got a good understanding of different kinds of arrays available in PHP. If you come across any problems feel free to contact me via codekadiya at gmail dot com. Play with arrays and try out more possibilities – Enjoy coding!

Post new comment