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

There are several ways to define arrays in php

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-06-07 14:09:30
Original
1830 people have browsed it

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'];
Copy after login

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'
];
Copy after login

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,因为数组长度不可修改
Copy after login

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'
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template