← Back to Chapters

PHP String Length & Count Functions

? PHP String Length & Count Functions

? Quick Overview

PHP provides built-in functions to measure string length and count array elements. The most commonly used are strlen() and count().

? Key Concepts

  • strlen() – Returns the number of characters in a string.
  • count() – Returns the number of elements in an array.

? Syntax / Theory

  • strlen(string) → integer length
  • count(array) → integer total elements

? Example 1: Using strlen()

? View Code Example
// Calculate length of a string
<?php
$string = "Hello World!";
$length = strlen($string);
echo $length;
?>

? Live Output / Explanation

The string Hello World! contains 12 characters including the space and exclamation mark.

? Example 2: Using count()

? View Code Example
// Count elements in an array
<?php
$array = array(1, 2, 3, 4);
echo count($array);
?>

? Live Output / Explanation

The array contains 4 elements, so count() returns 4.

? Interactive Example

Type text below to see character count (JavaScript simulation of strlen()):

Characters: 0

? Use Cases

  • Validating password or username length
  • Checking array size before loops
  • Form input validation
  • Pagination and data processing

✅ Tips & Best Practices

  • Use strlen() before trimming or formatting strings.
  • Use count() inside loops for dynamic array handling.
  • For UTF-8 strings, consider mb_strlen().

? Try It Yourself

  • Accept user input and display its length.
  • Create a multidimensional array and count its elements.
  • Compare strlen() vs mb_strlen().