Home > Backend Development > PHP Tutorial > Introduction to the usage of php array_chunk function (example)

Introduction to the usage of php array_chunk function (example)

王林
Release: 2023-04-09 12:52:02
Original
2571 people have browsed it

Introduction to the usage of php array_chunk function (example)

Function definition:

array_chunk() function can split an array into new array chunks and return a multi-dimensional numerical array, starting from 0, each Dimensions all contain size elements.

(Recommended tutorial: php graphic tutorial)

Syntax:

array_chunk(array,size,preserve_keys);
Copy after login
  • ##array Required. Specifies the array to use.

  • #size Required. An integer specifying how many elements each new array block contains.

  • preserve_key Optional.

    Possible values:

    true - Keep the key names from the original array.

    false - Default. Each new array block uses a zero-based index.

(Video tutorial recommendation:

php video tutorial)

Code example:

Now we need to split the array into An array block of two elements, retaining the key names from the original array.

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43","Harry"=>"50");
print_r(array_chunk($age,2,true));
?>
Copy after login

Output result:


Array
(
    [0] => Array
        (
            [Peter] => 35
            [Ben] => 37
        )

    [1] => Array
        (
            [Joe] => 43
            [Harry] => 50
        )

)
Copy after login

The above is the detailed content of Introduction to the usage of php array_chunk function (example). 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