How to unset old array keys and set new array by values of that array?

I’m beginner in PHP. I don’t know how to precisely elaborate this question , so i will try to visualy present the problem:

This is an array i have currently:

array(
    (int) 0 => array(
        (int) 2015 => '2015'
    ),
    (int) 1 => array(
        (int) 2016 => '2016'
    ),
    (int) 2 => array(
        (int) 2017 => '2017'
    ),
    (int) 3 => array(
        (int) 2018 => '2018'
    ),
    (int) 4 => array(
        (int) 2019 => '2019'
    ),
    (int) 5 => array(
        (int) 2020 => '2020'
    ),
    (int) 6 => array(
        (int) 2021 => '2021'
    ),
    (int) 7 => array(
        (int) 2022 => '2022'
    ),
    (int) 8 => array(
        (int) 2023 => '2023'
    )
)

I want output like this:

$array = [
    2015 => '2015',
    2016 => '2016' 
    etc..
];

Is it possible to get output like this?

>Solution :

You could do simple foreach loop:

<?php

$years = array(
    array(2015 => '2015'),
    array(2016 => '2016'),
    array(2017 => '2017'),
    array(2018 => '2018'),
    array(2019 => '2019'),
    array(2020 => '2020'),
    array(2021 => '2021'),
    array(2022 => '2022'),
    array(2023 => '2023')
);

foreach($years as $year) {
    $key = key($year);
    $value = current($year);
    $result[$key] = $value;
}

var_dump($result);

Output:

$result = [
    2015 => '2015',
    2016 => '2016',
    2017 => '2017',
    2018 => '2018',
    2019 => '2019',
    2020 => '2020',
    2021 => '2021',
    2022 => '2022',
    2023 => '2023'
];

Leave a Reply