skip to Main Content

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";

2

Answers


  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];
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search