Creating arrays in PHP

We will create an array and assign multiple values to this array like this
$my_data = array('mydata1','mydata2','mydata3', 'Mydata');
We can create an array with assigned Key and values like this.
$var=array(013=>"RKt",005=>"Bin",007=>"Alen");// Array to take customer name
$ar=array("FName"=>"John","Address"=>"Streen No 11 ","City"=>"Rain Town","Country"=>"USA");

Creating array by breaking string

We can create an array by breaking string. Let us try with some simple examples.
///Storing the sample paragraph in a variable /////
$string='plus2net provides easy tutorials for learning web programming';

$new_array=explode(" ",$string); // create an array by breaking string

// Let us display all elements of the array. ///
while (list ($key, $val) = each ($new_array)) { 
echo "$key -> $val <br>"; 
Here we have used space as delimiter and creaed the array by breaking the string. The output of above code is here.
0 -> plus2net 
1 -> provides 
2 -> easy 
3 -> tutorials 
4 -> for 
5 -> learning 
6 -> web 
7 -> programming
Now let us try another program. This is a keyword list, we will try to create array by breaking the string with coma as delimiter. Only changes to above code is shown here
$string='scripts , languages, programs, forms, database';
Output is here
0 -> scripts 
1 -> languages 
2 -> programs 
3 -> forms 
4 -> database 
If you want to know how many keywords are present by using array_size then here is the code.
echo "Total Number of words = ".sizeof($new_array);
Output of this is here
Total Number of words = 5

Creating array by using range()

We can specify a range and step to create an array by using numbers or chars between the range.
$my_array=range(0,10); // create an array
foreach ($my_array as $element) {
    echo $element . "  ";
0 1 2 3 4 5 6 7 8 9 10

Post your comments , suggestion , error , requirements etc here .

We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 All rights reserved worldwide Privacy Policy Disclaimer