Advent of code 2017/22
Ajax Direct

Answer

Part 1 :
Part 2 :
function solve($grid, $steps, $part2 = false) {
    $count = 0;
    $dir   = 0; // N, E, S, W
    [$x, $y] = [(int) floor(count($grid[0]) / 2), (int) floor(count($grid) / 2)];

    for ($i = 0; $i < $steps; $i++) {

        $grid[$y][$x] = $grid[$y][$x] ?? ".";

        $dir = match ($grid[$y][$x]) {
            "#" => Math::mod(($dir + 1), 4),
            "." => Math::mod(($dir - 1), 4),
            "F" => Math::mod(($dir + 2), 4),
            "W" => $dir
        };

        $grid[$y][$x] = match ($grid[$y][$x]) {
            "#" => $part2 ? "F" : ".",
            "." => $part2 ? "W" : "#",
            "F" => ".",
            "W" => "#"
        };

        if ($grid[$y][$x] == "#") $count++;

        match ($dir) {
            0 => $y--,
            1 => $x++,
            2 => $y++,
            3 => $x--,
        };
    }

    return $count;
}

// ==================================================
// > SOLUTIONS
// ==================================================
$grid = array_map("str_split", explode("\n", $input->string));
$solution_1 = solve($grid, 10_000);
$solution_2 = solve($grid, 10_000_000, true);