Home > Backend Development > PHP Problem > How to declare an array in php

How to declare an array in php

PHPz
Release: 2023-05-19 14:14:08
Original
630 people have browsed it

Declaring an array in PHP is very simple and can be done in two ways: direct assignment and the array() function.

  1. Direct assignment method

Using the direct assignment method, you can define and initialize an array in one statement. The syntax is as follows:

$myArray = array("apple", "banana", "orange");
Copy after login

The above statement defines and initializes an array containing three elements, namely "apple", "banana" and "orange". Array elements can be any type of data, including strings, numbers, Boolean, etc.

  1. Use the array() function

Use the array() function to define arrays more flexibly and add or remove elements in later code. The syntax is as follows:

$myArray = array();
$myArray[0] = "apple";
$myArray[1] = "banana";
$myArray[2] = "orange";
Copy after login

The above statement first defines an empty array $myArray, and then adds three elements to it using array subscripts, namely "apple", "banana" and "orange".

In addition to using numeric subscripts, you can also use string subscripts to define array elements, for example:

$fruits = array(
    "apple" => "red",
    "banana" => "yellow",
    "orange" => "orange"
);
Copy after login

The above statement defines an associative array $fruits containing three elements, each The element consists of a fruit name and a color.

Summary

Whether it is direct assignment or the array() function, PHP's array definition is very simple and can easily handle large amounts of data. Therefore, in PHP development, arrays are widely used to store and manipulate data.

The above is the detailed content of How to declare an array in php. For more information, please follow other related articles on the PHP Chinese website!

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