Three types of array
$my_data = array('mydata1','mydata2','mydata3', 'Mydata');
In this array the index associated with each element is incremental numbers starting from 0.
echo $my_data[2] // mydata3
=> operator to associate key with its value.
$var=array(013=>"RKt",005=>"Bin",007=>"Alen");// Array key with value
$ar=array("FName"=>"John","Address"=>"Streen No 11 ",
"City"=>"Rain Town","Country"=>"USA");
Output from this array is here,
echo $var[007]; // Alen
echo "<br>";
echo $ar["City"]; // Rain Town
Multidimensional arrays are discussed here.
///Storing the sample paragraph in a variable /////
$string = 'plus2net provides easy tutorials for learning web programming';
$newArray = explode(' ', $string);
foreach ($newArray as $key => $val) {
echo "$key -> $val<br>";
}
Here we have used space as delimiter and created 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';
$new_array=explode(",",$string);
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
$my_array=range(0,10); // create an array
foreach ($my_array as $element) {
echo $element . " ";
}
Output
0 1 2 3 4 5 6 7 8 9 10
range() with step & chars:
$nums = range(0, 10, 2); // 0 2 4 6 8 10
$chars = range('a', 'f'); // a b c d e f
$a = [1, 2];
$b = [3, 4];
$merged = [...$a, ...$b]; // [1,2,3,4]
print_r($merged);
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.