Search code examples
phparrayssubstr

Get the first 4 digits of each element of an array


I have an array which i got from an sql database, and each element is saved as YYYY-MM-DD. but i only need the year of each element. My current code:

if(isset($_GET['date'])){
$dates= unserialize(urldecode($_GET['date']));
foreach($dates as $i){
$year = substr($i, 0, 4);
}}
print_r($year);

but when i run the code it only gives me the year of the first element

i already tried array_slice but that didnt work either


Solution

  • if(isset($_GET['date'])) {
        $dates= unserialize(urldecode($_GET['date']));
        $year = array();
        foreach($dates as $i) {
            $year[] = substr($i, 0, 4);
        }
    }
    print_r($year);
    

    2 little changes that will fix it.