Home >Backend Development >PHP Problem >How to define array variables in php (two ways)

How to define array variables in php (two ways)

PHPz
PHPzOriginal
2023-04-20 13:54:33847browse

In PHP, the following two ways can be used to define array variables:

  1. Indexed array

Indexed array is the most common array type. It is an ordered, countable array in which each element has a unique numerical index. To define an index array, you can use the following syntax:

$arrayName = array(value1, value2, value3, ..., valueN);

where, $arrayName is the array variable name, value1, value2, value3......valueN is the element in the array. To access elements in an array, you use their numerical index. For example, to access the first element in $arrayName, you would use the following syntax:

echo $arrayName[0];
  1. Associative array

Associative array is a special type in PHP. It is an unordered, countable array where each element has a unique string index. To define an associative array, you can use the following syntax:

$arrayName = array(
    key1 => value1,
    key2 => value2,
    key3 => value3,
    ...,
    keyN => valueN
);

where, $arrayName is the array variable name, key1, key2, key3……keyN is the key of the element in the array, value1, value2, value3…… valueN is the value of the element in the array. To access elements in an array, you use their string index. For example, to access the element named "name" in $arrayName, you can use the following syntax:

echo $arrayName["name"];

The above are two ways to define array variables, and you can use different ways according to actual needs.

The above is the detailed content of How to define array variables in php (two ways). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn