Hướng dẫn dùng arrays examples trong PHP

  • Trang chủ
  • Phát triển web
  • PHP
  • Hàm array() trong PHP

Hướng dẫn cách sử dụng hàm array() về mảng trong lập trình PHP

Tác dụng của hàm array()

The array() function creates an array.

It is a language construct used to represent literal arrays, it is not a regular function.

The following table summarizes the technical details of this function.

Return Value:Returns an array of the parameters.
Version:PHP 4+


Syntax

The basic syntax of the array() function is given with:

array(index=>value, index=>value, ...);

The index may be of type string or integer. When indices are integers array is called indexed array, and when indices are strings array is typically called associative array.

When index is omitted or not specified, an integer index is automatically generated, starting from 0. If index is an integer, next generated index will be the bigger integer (previous index + 1). Also, if two identical index are defined, the last one overwrites the previous one.

The following example shows the array() function in action.


Parameters

The array() function accepts the following parameters.

ParameterDescription
index => value Specifies the index (string or integer) and its associated value.
... Specifies more indices and values.


More Examples

Here're some more examples showing how array() function is used to create arrays:

The following example shows how to create an indexed array (i.e. array with integer indices).

The following example shows how to create an associative array (i.e. array with string indices).

"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");
print_r($alphabets);
?>

The following example shows how to create a multidimensional array (an array of arrays).

 array("cat", "dog", "cow", "horse"),
    "wild" => array("lion", "tiger", "zebra")
);
print_r($animals);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới