Home  >  Article  >  Backend Development  >  There are several ways to define arrays in php

There are several ways to define arrays in php

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-07 13:44:521782browse

There are four ways to define an array in php: 1. Numeric index array, using integers as array subscripts, and storing each element in a sequential numbering manner; 2. Associative arrays, using strings as array subscripts Mark, store each element in the form of one-to-one correspondence between name and value; 3. Fixed-length numeric index array supported starting from PHP 7.4; 4. Use the list() function to deconstruct the array into multiple variables.

There are several ways to define arrays in php

Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.

PHP There are 4 ways to define arrays:

1. Numeric index array: use integers as array subscripts and store each element in a sequential numbering manner.

$names = array('John', 'Jane', 'Jim');
// 或者在PHP 5.4及以上版本中可以简写成
$names = ['John', 'Jane', 'Jim'];

2. Associative array: Use strings as array subscripts to store each element in a one-to-one correspondence between name and value.

$info = array(
    'name' => 'John',
    'age' => 30,
    'location' => 'New York'
);
// 或者在PHP 5.4及以上版本中可以简写成
$info = [
    'name' => 'John',
    'age' => 30,
    'location' => 'New York'
];

Note that arrays can also be defined in the following ways in PHP:

3. Fixed-length numeric index arrays supported starting from PHP version 7.4 (these arrays cannot add or delete elements, just Like a read-only constant):

$scores = [10, 20, 30]; // 这是一个长度为 3 的数组
$scores[] = 40;         // 这里会导致 Fatal error,因为数组长度不可修改

4. Use the list() function to deconstruct the array into multiple variables:

$info = array('John', 30, 'New York');
list($name, $age, $location) = $info;
echo $name;      // 输出 'John'
echo $age;       // 输出 30
echo $location;  // 输出 'New York'

The above is the detailed content of There are several ways to define arrays in php. 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