Home > Backend Development > PHP Problem > There are several types of PHP array definitions

There are several types of PHP array definitions

王林
Release: 2023-02-24 13:36:01
Original
3066 people have browsed it

There are several types of PHP array definitions

1. array() function

1.1 No key value

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

1.2 Key-value pair

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

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

first: minimum value of element

second: maximum element 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

Recommended tutorial: PHP video tutorial

The above is the detailed content of There are several types of PHP array definitions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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