0
0
PHPprogramming~10 mins

String length and counting in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String length and counting
Start with a string
Call strlen() function
Count characters in string
Return length as integer
Use length for output or logic
End
This flow shows how PHP counts the number of characters in a string using strlen(), then returns that count for use.
Execution Sample
PHP
<?php
$str = "Hello";
$len = strlen($str);
echo $len;
?>
This code counts the characters in "Hello" and prints the length.
Execution Table
StepActionVariableValueOutput
1Assign string to $str$str"Hello"
2Call strlen() on $strstrlen($str)5
3Assign length to $len$len5
4Print $len$len55
5End of script---
💡 Script ends after printing the length 5.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
$strundefined"Hello""Hello""Hello"
$lenundefinedundefined55
Key Moments - 2 Insights
Why does strlen("Hello") return 5 and not 4 or 6?
Because strlen counts every character including letters and spaces exactly once. In the execution_table step 2, strlen("Hello") counts 5 letters: H, e, l, l, o.
What if the string is empty? What does strlen return?
If the string is empty (""), strlen returns 0 because there are no characters. This would be shown in step 2 with strlen("") = 0.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $len after step 3?
Aundefined
B5
CHello
D0
💡 Hint
Check the 'Variable' and 'Value' columns at step 3 in execution_table.
At which step is the string length printed to output?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look for the step where Output column shows '5' in execution_table.
If $str was "Hi!", what would strlen($str) return?
A2
B4
C3
D5
💡 Hint
Count the characters in "Hi!" as done in execution_table step 2.
Concept Snapshot
strlen(string) returns the number of characters in a string.
Assign string to a variable.
Call strlen() with the string variable.
Store the result in another variable.
Use or print the length as needed.
Full Transcript
This example shows how PHP counts the length of a string using strlen(). First, a string "Hello" is stored in $str. Then strlen($str) counts the characters and returns 5. This value is saved in $len. Finally, $len is printed, showing 5. The process counts each character exactly once. If the string was empty, strlen would return 0. This helps in many tasks like validation or loops.