How can one select every nth character from a string in PHP?

To select every nth character from a string in PHP, you can iterate through the string using a loop and append every nth character to a new string. One way to achieve this is by using a for loop with a step size of n to access every nth character in the string.

function selectNthCharacters($string, $n) {
    $selectedCharacters = '';
    for ($i = 0; $i < strlen($string); $i += $n) {
        $selectedCharacters .= $string[$i];
    }
    return $selectedCharacters;
}

$string = "Hello, World!";
$n = 2;
$result = selectNthCharacters($string, $n);
echo $result; // Output: "Hlo ol!"