Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to clone a two-dimensional array in PHP

3 Answers

0 votes
$Array2D = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9, 10]
];

$clonedArray = array_map('array_slice', $Array2D, array_fill(0, count($Array2D), 0));

print_r($clonedArray);

 
 
/*
run:
 
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
            [3] => 10
        )
)
 
*/

 



answered Mar 7, 2025 by avibootz
0 votes
$Array2D = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9, 10]
];

$clonedArray = [];
foreach ($Array2D as $subArray) {
    $clonedArray[] = $subArray;
}

print_r($clonedArray);

 
 
/*
run:
 
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
            [3] => 10
        )
)
 
*/

 



answered Mar 7, 2025 by avibootz
0 votes
$Array2D = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9, 10]
];

$clonedArray = array_map(function($subArray) {
    return array_merge([], $subArray);
}, $Array2D);

print_r($clonedArray);

 
 
/*
run:
 
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
            [3] => 10
        )
)
 
*/

 



answered Mar 7, 2025 by avibootz

Related questions

1 answer 73 views
3 answers 90 views
1 answer 69 views
1 answer 76 views
1 answer 85 views
3 answers 103 views
3 answers 91 views
...