If you are programmer then you dont need introduction of array. In every language array is the most important part.
how to work with multidimensional array in php
Using array we can achieve so many things and array is useful for so many times when we do programming.
In this article I am going to share some method about PHP array.
What is PHP array?
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Following is syntax
array(key => value)
Creating PHP array:
<?php $arr = array("str_arr" => "this is string", 25 => true); echo $arr["str_arr"]; // print this is string echo $arr[25]; // print ture ?>
How to print direct PHP array.
<?php $arr=array("a"=>"jimi","b"=>"timi","c"=>"limi"); print_r($arr); ?>
How to print PHP array preformated
<?php $arr=array("a"=>"jimi","b"=>"timi","c"=>"limi"); print_r("<pre>".$arr); ?>
How to create a two-dimensional PHP array
<?php $arr = array ( "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third") ); print_r("<pre>".$arr); ?>
How to create an array from MySql table
<? function cre_array($row) { foreach($row as $key => $value) { global $$key; $$key = $value; } } //User table has first_name field present. $sql = mysql_query("SELECT * FROM 'users'"); while ($row = mysql_fetch_assoc($sql)) { cre_array($row); echo $first_name.'<br>'; //instead of $row['first_name'] } ?>
How to count PHP array count
$fruits = array("a" => "orange", "b" => "banana", "c" => "apple"); echo sizeof($fruits); echo $arrayLength = count($fruits);
PHP and MySql and Array
<?php $sql = "SELECT key,value FROM table"; $result = mysql_query($sql); while($row = mysql_fetch_row($result)) { $myArray[$row[0]] = $row[1]; } while(list($key,$value) = each($myArray)) { echo "$key : $value"; } ?>
Following image will help you to understand two dimensional array.