Showing posts with label populating. Show all posts
Showing posts with label populating. Show all posts

Monday, 29 February 2016

How to Create an Array in PHPIn Feburary 2016 29,

In Feburary 2016 29,
Imagine that you have to write a movie catalog. One of the variables that you will use in your program is the movie title. But if you have thousands of movies, using a separate variable to store each title is not ideal. Instead, you should use one variable (the title) which has many values ('One Flew Over the Cuckoo's Nest,' 'The Graduate' and so on). Such data is an ideal candidate for an array.
Check to see if you already have a list of values, so that you can create the array with the array function instead of populating it manually.
Create the Array
Declare the array and assign values:
$titles = array('Hair', 'The Office', 'Troy', 'Tarzan', 'American Pie', 'Adam and Eve', 'Mystery', 'E.T.', 'Star Wars');
Enter as many movie titles as you have. If your values are strings, as in the above example, don't forget the quotes around them. If your values are integers, you can forgo the quotes.
Appreciate that this array is created with numeric indexing. In the above example, the array has nine elements (movie titles) and the indexes are from 0 ('Hair') to 8 ('Star Wars'). However, you can also create associative arrays.
Create an associative array. An associative array uses textual keys instead of numbers, and the indexes are more descriptive. This is especially useful when the values are not strings. The general syntax is the following:
$salary['John Smith'] = 3000;
This will assign the value 3000 to the array element, which has the 'John Smith' index.
Use the array function to create the array.
$salary = array('John Smith' => 3000, 'Sally Jones' => 4000, 'Chris Steward' => 4900, 'Mary Roberts' => 6500, 'Sam Moses' => 5400, 'Alice Roberts' => 4200);
Notice the slight difference in the syntax: You use the => symbol to enter the value for the key.
Perform Simple Operations With the Array
Reference values from the array by their index. For instance, if you want to display the title 'Adam and Eve,' you would do the following:
echo $titles[5];
because 'Adam and Eve' is the sixth element in the array and its index is 5.
Assign values to array elements. If you want to set a new value for an array element, use the following:
$titles[6] = 'Midnight Express';
This will replace the 'Mystery' value with 'Midnight Express'.
In Feburary 2016 29,