Home > Backend Development > PHP Tutorial > Commonly used array functions in PHP

Commonly used array functions in PHP

不言
Release: 2023-04-02 16:08:02
Original
3375 people have browsed it

This article mainly introduces the commonly used array functions in PHP, which has certain reference value. Now I share it with you. Friends in need can refer to it

1. array_fill(index,number,value ) Fill the array with values

Parameter description:

Index: The first index value of the returned array

Number: Specifies the number of elements to be inserted

 value: The value used to fill the array

<?php
$a1=array_fill(3,4,"blue");
print_r($a1);
?> 
Copy after login

Run result:

Array ( [3] => blue [4 ] => blue [5] => blue [6] => blue )

2. array_combine($keys,$values) merge array

Parameter description:

$keys: Key name array

$values: Key value array

<?php
$fname=array("Bill","Steve","Mark");
$age=array("60","56","31");

$c=array_combine($fname,$age);
print_r($c);
?>
Copy after login

Run result:

Array ( [Bill] => 60 [Steve] => 56 [Mark] => 31 )

3. array_intersect_key($arr1,$arr2,$arr3...) compares two or more The key names of arrays, return the intersection

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pink");

$result=array_intersect_key($a1,$a2);
print_r($result);
?>
Copy after login

Return result:

Array ( [a] => red [c] => ; blue )

4. array_shift($arr) deletes the first element in the array and returns the deleted element

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);
print_r ($a);
?>
Copy after login

return Result:

redArray ( [b] => green [c] => blue )

5, array_walk($arr,function($value,$key){}) function Apply a callback function to each element in the array

To change the value in the array, you need to use a reference type&$value

<?php
function myfunction(&$value,$key)
{
$value="yellow";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
print_r($a);
?>
Copy after login

to return the result :

Array ( [a] => yellow [b] => yellow [c] => yellow )
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Introduction to PHP namespaces

Introduction to PHP file programming

The above is the detailed content of Commonly used array functions in PHP. 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