w3resource

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


14. Print Next Character with Wrap-Around

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

For more Practice: Solve these Related Problems:

  • Write a PHP script to display the next character in the alphabet for a given letter, ensuring that 'z' wraps around to 'a'.
  • Write a PHP function that takes a character as input and returns the subsequent character, handling upper and lower case separately.
  • Write a PHP program to generate a sequence of next characters for a given string and output the transformed string.
  • Write a PHP script to simulate a cyclic alphabet transformation where every letter is replaced by its successor, wrapping 'z' to 'a' automatically.

Go to:


PREV : Extract Filename Component from URL.
NEXT : Remove Part of String from Beginning.

PHP Code Editor:



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

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.