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

How to create an array in php

藏色散人
藏色散人 Original
2019-10-14 09:38:50 3086browse

How to create an array in php

How to create an array in php?

Several ways to create an array in php

1. array() function

1.1 No key value

  $arr=array(1,2,3,4);

1.2 Key-value pairs

$arr=array(    'name'=>'myj',    'age'=>'18',    'phone'=>'1888888888'  );

1.3 Empty array

 $arr=array();

2. compact() function

The compact function can convert variables into arrays.

$a = 'aaa'; $b = 'bbb'; $c = 'ccc'; $arr3 = compact('a','b','c');

Output:

{"a":"aaa","b":"bbb","c":"ccc"}

3. array_combine() function

array_combine() function can combine two arrays into a new array, where One of the arrays is the key name, and the value of the other array is the key value.

$arr_key = array('a','b','c','d'); $arr_val = array('1','2','3','4'); echo var_dump(array_combine($arr_key,$arr_val));

Output:

'a' => string '1' (length=1) 'b' => string '2' (length=1) 'c' => string '3' (length=1) 'd' => string '4' (length=1)

4. Use the array_fill() function to create an array

The array_fill() function fills the array with a given value class

Definition format:

array_fill(start,number,value)

start: starting index

number: number of arrays

value: array value

Example:

$a=array_fill(2,3,"Dog"); print_r($a);

Output result:

Array ( [2] => Dog [3] => Dog [4] => Dog )

5. Range() function

Definition format: array range(first, second, step) first: Element minimum value second: element maximum value step: element step size (default 1)

$arr = range(1,5); 输出:[1,2,3,4,5] $arr = range(1,15,3); 输出:1,4,7,10,13

For more PHP-related knowledge, please visitPHP Chinese website!

The above is the detailed content of How to create 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
Previous article:What is php format Next article:What is php format