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

Commonly used array functions in PHP

不言
不言Original
2018-07-06 09:34:363350browse

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);
?> 

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);
?>

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);
?>

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);
?>

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);
?>

to return the result :

Array ( [a] => yellow [b] => yellow [c] => yellow )

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!

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