Home  >  Article  >  Backend Development  >  How to set an array in php

How to set an array in php

藏色散人
藏色散人Original
2020-10-29 10:23:272524browse

How to set the array in php: 1. Set the array through [array name=array('value', 'value', 'value',...);]; 2. Through [$array name[ ] = 'value';] method to set the array; 3. Through [$array name = array (numeric type key => 'value'...)] method, etc.

How to set an array in php

Recommended: "PHP Video Tutorial"

6 ways to create arrays in php

The first format

$数组名称 = array(‘值’, ‘值’, ‘值’,……);

This format does not specify the key of the element in the array. PHP will automatically create the key in the form of a number, starting from 0 and accumulating in sequence.

Format of calling array: $array name[numeric key]

<?php 
$arr = array(&#39;a&#39;,&#39;b&#39;,&#39;c&#39;); 
echo $arr[1]; 
//输出b

Second format

$数组名称[] = ‘值’;
$数组名称[] = ‘值’;
$数组名称[] = ‘值’;
……

This format also does not specify the key of the element in the array, PHP Keys are automatically created in the form of numbers, starting from 0 and counting up.

Format of calling array: $array name[numeric key];

<?php 
$arr[] = &#39;a&#39;; 
$arr[] = &#39;b&#39;; 
$arr[] = &#39;c&#39;; 
echo $arr[1]; 
//输出b

3rd format

$array name=array(numeric key=> 'Value', key of numeric type=> 'Value', key of numeric type=> 'value',...);

Calling format: $array name[key of numeric type];

<?php 
$arr = array(1=>&#39;jack&#39;,2=>&#39;lucy&#39;,500=>&#39;hcoder&#39;); 
echo $arr[500]; 
//输出hcoder

This format uses integers as the keys of the array. PHP's support for arrays is very flexible, and the numbers in the array can be defined arbitrarily.

If there are duplicate keys in the array, the last element will overwrite all previous keys, and the last one will be a valid value.

The 4th format

$数组名称[整数类型键] = ‘值’;
$数组名称[整数类型键] = ‘值’;
$数组名称[整数类型键] = ‘值’;
……

Calling format: $array name[integer type key];

<?php 
$arr[1] = &#39;jack&#39;; 
$arr[2] = &#39;lucy&#39;; 
$arr[500] = &#39;hcoder&#39;; 
echo $arr[500]; 
//输出hcoder

The 5th format (associative array)

$数组名称=array(‘字符串形式的键’=>’值’,‘字符串形式的键’=>’值’,……);

Calling format: $array name['key in string form'];

<?php 
$arr = array(&#39;name&#39;=>&#39;张三&#39;, &#39;age&#39;=>18);
echo $arr[&#39;age&#39;]; 
//输出18

The 6th format (associative array)

$数组名称[ ‘字符串形式的键’]=>’值’;
$数组名称[ ‘字符串形式的键’]=>’值’;
……

Calling format: $array name['string form The key'];

<?php 
$arr[&#39;name&#39;] = &#39;张三&#39;; 
$arr[&#39;age&#39;] = 18; 
echo $arr[&#39;age&#39;]; 
//输出18

The above is the detailed content of How to set an array 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