-4

I am trying to minus or subtract by 1 the academic year of school year with this format, e.g. "2020-2021"

If it is 2020-2021, I would like to change it 2019-2020. Is there a way to solve this concern?

I considered trying to subtract using a hyphenated expression, but I am pretty stuck.

echo "2020-2021"-"1-1";
echo "Result: 2019-2020";
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
jovlog
  • 1
  • 1
  • 2
    [Split](https://www.php.net/manual/en/function.explode.php), [parse](https://www.php.net/manual/en/function.intval.php), subtract each then just recombine them. – Martheen Nov 28 '22 at 05:59

2 Answers2

1

You can use explode and parse the value to subtract the value

    $minusYear = 1;
    $myString = "2020-2021";
    $myArray = explode('-', $myString);
  
  
    foreach($myArray as $k => $v)
    {
      $myArray[$k] = (int) $myArray[$k] - $minusYear;
    }
  
    echo "Result ".$myArray[0]."-".$myArray[1];
Xun
  • 377
  • 1
  • 7
1

You don't need to complicate your task by trying to shoehorn 1-1 into your approach. Use preg_replace_callback() to target and decrement numeric substrings in one line of code.

This approach targets the numbers and therefore will not break if your delimiting character(s) change.

Code: (Demo)

$yearSpan = '2020-2021';

echo preg_replace_callback('/\d+/', fn($m) => --$m[0], $yearSpan);

Decrementing the fullstring match --$m[0] could also be written as simple subtraction: $m[0] - 1.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136