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

How to create an array in php

藏色散人
Release: 2023-02-26 14:12:01
Original
3195 people have browsed it

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

1.2 Key-value pairs

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

1.3 Empty array

 $arr=array();
Copy after login

2. compact() function

The compact function can convert variables into arrays.

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

Output:

{"a":"aaa","b":"bbb","c":"ccc"}
Copy after login

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

Output:

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

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

Output result:

Array ( [2] => Dog [3] => Dog [4] => Dog )
Copy after login

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

For more PHP-related knowledge, please visit PHP 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!

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