Reverse String and Empty String in PHP

Introduction

In this article I describe how to use PHP to reverse a string and how to determine whether a string is empty. To learn some other string functions, go to:

  1. String Functions in PHP: Part1
     
  2. String Functions in PHP:Part2
     
  3. String Functions in PHP:Part3
     
  4. String Functions in PHP:Part4
     
  5. String Functions in PHP:Part5
     
  6. String Functions in PHP:Part6
     
  7. String Functions in PHP:Part7
     
  8. String Functions in PHP:Part8
     
  9. String Functions in PHP:Part9
     
  10. String Functions in PHP:Part10

Reverse string

To reverse a string you can simply use the strrev() function.

Example

The following example shows how to reverse a string using the strrev() function. The strrev() function takes a string argument like "PHP nrael I" and returns the entire string in reverse order like "I learn PHP".

<?php

// define string

$str = "PHP nrael I";

// reverse string

// result: "detpecca sserpxE naciremA dna draCretsaM ,asiV"

$revstr = strrev($str);

echo $revstr;

?>

Output

reverse-string-in-php.jpg

Checking for an empty string value

If you want to determine if a string is empty then use a combination of PHP's isset() and trim() functions.

Example

In the following example the isset() function verifys that the string variable exists and then uses the trim() function to trim white spaces from the edges and equate it to an empty string.

<?
php
//
define string
$
str = " ";
//
check if string is empty
//
result: "Empty"
echo
(!isset($str) || trim($str) == "") ? "String is Empty" : "String is not Empty";
?>

Output

empty-string-in-php.jpg 

Up Next
    Ebook Download
    View all
    Learn
    View all