Posted By:
7 Mar, 2014 11:39 am PST

How to create array in php?

How to create array in php?

Array is collection of information represented by single variable name. If you want to store data , that is belongs to same domain or category in such situation you can store multiple elements of information using single variable name.

Syntax:-

$arrayName=array();

This general syntax of creating array; There three types of array

a)      Indexed array:-

These arrays are with number index, like 0,1,2,3,…Index can be assigned manually or automatically.

Syntax:-

$arrayName=array(value1, value2,value3,…);

 

b)      Associative array

arrays are with user defined named index, like “first”, “second”,”fname”, “lname”…

Syntax:-

$arrayName=array(“indexName1”=> value1, “indexName2” => value2, “indexName3”=> value3,…);

 

c)       Multidimensional array

Contains one or more array in the one dimensional array.

Syntax:-

 

$arrayName=array(array(value1,value2…), array(value1,value2…),….);

 

Write your code here

<?php 

echo "<h2>";

echo "To demonstrate Indexed ,Associative , Multidimensional array <br><br>";

$indexedArray = array(100,200,300,400,500)// indexed Array

 

$assoctArray = array(100=>"Clitus", 200=>"Oliver", 300=>"Manish" ,400=>"Joyce",500=>"Ancy"); // //Associative Array

$multidiaArray = array("Clitus"=>array(40,60,70),"Oliver"=>array(40,80,90),"Manish"=>array(50,90,70),"Joyce"=>array(50,70,60),"Ancy"=>array(90,80,60)); // Multidimensional Array

 

echo "<pre>";

 

foreach($indexedArray as $rollno)

{

 

$name=$assoctArray[$rollno];

$marks = $multidiaArray[$name];

 

echo "Roll No: {$rollno} <br>";

echo "Name : {$name} <br>";

echo "Marks Obtained in three subject <br>" ;

 

$total = 0;

foreach($marks as $tempMark)

{

echo " {$tempMark} <br>";

$total =$total + $tempMark;

}

echo "Total is {$total}<br><br>";

}

?>

ArrayPHP.php

ArrayPHP

Attachment: ArrayPHP.php


How to use array in PHP?

As we studied array in various languages like C++,Java similarly in PHP  is used to store multiple values in single variable. It can store integer,string etc and their index will also be represented in integer value. 


//To store engineering branches name in array and display them on screen 

<!DOCTYPE html>

<html>

<body>

<?php

$branch = array("CSE","CIVIL","CHEMICAL","MECHANICAL");

echo "Engineering Branches : " . $branch[0] . ", " . $branch[1] . "," . $branch[2]." and " . $branch[3] . ".";

?>

</body>

</html>


/*Output of the above program is:

Engineering Branches : CSE, CIVIL,CHEMICAL and MECHANICAL.

*/

Attachment: array.php
Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud