w3resource

PHP String Exercises: Print the next character of a specific character

PHP String: Exercise-14 with Solution

Write a PHP script to print the next character of a specific character.

Visual Presentation:

PHP String Exercises: Print the next character of a specific character

Sample character : 'a'
Sample character : 'z'

Sample Solution:

PHP Code:

<?php
$cha = 'a';
$next_cha = ++$cha; 
//The following if condition prevent you to go beyond 'z' or 'Z' and will reset to 'a' or 'A'.
if (strlen($next_cha) > 1) 
{
 $next_cha = $next_cha[0];
 }
echo $next_cha."\n";
?>

Output:

b

Explanation:

The above PHP code snippet increments a character stored in the variable '$cha' to the next character in the ASCII sequence using the pre-increment operator '++$cha'. It then checks if the resulting string length is greater than 1, which would occur if the character overflows beyond 'z' or 'Z'. If so, it resets the character to 'a' or 'A'. Finally, it outputs the next character.

Flowchart :

Flowchart: Print the next character of a specific character

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to get the filename component of the specified path.
Next: Write a PHP script to remove a part of a string from the beginning.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.