PHP Tutorial





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
PHP Topics
Introduction Introduction
Syntax Syntax
Data Types Data Types
Operators Operators
Control Structures Control Structures
Functions Functions
Pre-defined Function Pre-defined Function
Calendar Functions Calendar Functions
Date and Time Date and Time
Array Functions Array Functions
Array List Array Functions List1
Array Function List Array Functions List2
Math Functions Math Functions
PHP MYSQL Functions PHP Mysql Functions
File Handling File Handling
Error Handling Error Handling
DB Size DB Size
PHP Mail PHP Mail
String Tokens String Tokens
String Functions String Functions
String Functions List String Functions List1
String Functions List2 String Functions List2
Session Functions Session Functions
Cookies Functions Cookies Functions
Form Variables Form Variables
Running PHP from JS Running PHP from JS
Array To JS Array To JS
JS Array Array to PHP
Encryption Encryption
Common Header Common Header
Forums Ask Your Doubts
Scraps More about PHP
Feedback Feedback
 




Array datatype in PHP


Tutorials »Php »

Topic

How to define an array variable and assign value?



Explanation

An array is a compound data type that can contain multiple data values. Each array element can be retrieved by using the array variable name and its key/index value. The index value may be either numeric value or string value.

An array variable can be declared as

$val=3;
$arrayname = array( "first element", 2,$val );
echo $arrayname[0]; //prints: first element
echo $arrayname[1]; //prints: 2
echo $arrayname[2]; //prints: 3


Array values can hold values with different data type. As you see in the previous example, elements in an array can be any data type(string, integer, double). Array index always starts at position zero,so the first array element has an index of 0 and the last element has an index one less than the number of elements in the array. You can also use print_r($arrayname) function to print the values of an array.

PHP allows you to add an element at the end of an array without specifying an index.

For example:

$arrayname[] ="Test";

In this case, the "Test" element is given the index 3 in our $arrayname array. If the array has non-consecutive elements, PHP selects the index value that is one greater than the current highest index value.

Arrays indexed using strings are called as associative arrays

Example:

$arr["Jan"]=1;
$arr["Feb"]=2;


we cannot use a simple counter in a for loop to work with this array. We can use the foreach loop or print_r() function. In the following example we use the foreach loop to iterate through our associative array.

foreach($arr as $arrval=>$val)
{
echo "$val";
}






Other Links

web hosting