Gray Hat World - Internet Marketing Forum

Full Version: PHP Working with arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!
Its me again!
With yet another useful tutorial for php. This time we will take a little look at the arrays in php. How to use, them, and not get scared!

Lets start with the simplest example:
Code:
<?php
$arr = array("myarraykey" => "myarrayvalue", 2 => true);

echo $arr["myarraykey"]; // myarrayvalue
echo $arr[2];    // 1
?>
What does the code above do?
Well its pretty simple. First we create a new array with 2 values. Then we display the values in the browser.

Each value in array has a key, array keys are optional, if not declared they are automatically incremental, starting from 0, meaning that if we do only:
Code:
$arr = array(1,2);
Our array will contain the values of 1 and 2, in the respective keys 0 and 1.
So if we follow that logic if we do:
Code:
$arr = array(1,2);
echo $arr[0]; // 1
echo $arr[1]; // 2
The code above will display to the browser the 2 values of the array. We get the values by the keys associated with them. In this case the auto generated incremental keys Smile In the first example we created a so called associative array. Meaning that we put a "known" name to each key, for the respective value.
This way is preferred for us if we describe stuff, like objects, items, etc.
And the auto incremental keys are preferred when we have multiple arrays that we like to be in a array Smile (i know it sounds complicated but bare with me).
So an example is needed to clarify things Smile
Code:
$arr = array(array('name' => 'john', 'age' => 20), array('name' => 'bruce', 'age' => '15'));
echo $arr[0]['name']; // john
echo $arr[1]['name']; // bruce
echo $arr[0]['age']; // 20
Basically its like a list with candidates Smile Each item on the list has several properties, in our case the properties are name and age.

Again this is a very basic usage case. Arrays are very powerful, they can represent basically any set of items, objects, persons and so on. Mastering them is very important for knowing your way around in solving php problems Smile
Good tutorial, +reped! Smile
Nice Tut
With PHP, we only have arrays. They are very simple. It is something like a list of items, where each entry has two properties: A key and a value. If you have the key, you can access a value directly - otherwise, you will have too look for it. PHP allows us unlimited dimensions of arrays, which means that we can have an array that has a range of arrays, which have a range of arrays, and so on.
Yeah Nice Tut Ill Try.
Perfect TUTorial
Reference URL's