Home  >  Article  >  Backend Development  >  How to change the subscript of php array

How to change the subscript of php array

藏色散人
藏色散人Original
2021-06-16 09:17:583250browse

How to change the subscript of a php array: first create a PHP sample file; then define two arrays; finally modify and rearrange the array subscripts through the "array_merge($a1,$a2)" method.

How to change the subscript of php array

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to change the subscript of the php array? Use array_merge to rearrange array subscripts

I used an array_unique to remove duplication in an array, but found that the subscript retained the subscript of the original array

But javascript requires subscripts when using a for loop Neat, so looking for a way to rearrange array subscripts

array_merge can solve this problem

array_merge() function merges two or more arrays into one array.

If the key name is repeated, the key value of the key will be the value corresponding to the last key name (the later one will overwrite the previous one). If the array is numerically indexed, the key names are re-indexed consecutively.

Note: If only an array is input to the array_merge() function, and the key name is an integer, the function will return a new array with integer key names, and the key names will be re-indexed starting from 0. (See Example 2)

Syntax

array_merge(array1,array2,array3...)

Parameters

array1 Required. The first array of input.

array2 Required. The second array of input.

array3 Optional. Multiple input arrays can be specified.

Example 1

<?php
$a1=array("a"=>"Horse","b"=>"Dog");
$a2=array("c"=>"Cow","b"=>"Cat");
print_r(array_merge($a1,$a2));
?>

Output:

Array ( [a] => Horse [b] => Cat [c] => Cow )

Example 2

Use only one array parameter:

<?php
$a=array(3=>"Horse",4=>"Dog");
print_r(array_merge($a));
?>

Output:

Array ( [0] => Horse [1] => Dog )

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to change the subscript of php array. 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