PHP Developer – strlen, count, and substr
The strlen function retuns the length, i.e. number of characters in a string: int strlen(string s)
count will get the number of elements in an array: int count(array a)
substr will return a “subset” of a string, string substr(string s, int start, [int len]);
<?php
$s = “test string”;
echo “String length is: ” . strlen($s);
?>
Will return: String length is: 11
Why would you care how long a string is? Well, for many reasons, one being that you might wish to iterate through each character of a string to perform a certain conditional check or operation on each character. Alternatively, you might want to check that a certain string is not over a given size, and if so, shorten it. Here’s a common example that shows these three common functions together:
<?php
$myarray = Array("This is a very long string", "short string", "some text", "some more text to be shortened");
define(MAXLEN, 20); //maximum permitted string length
$num = count($myarray); //Get the number of elements in the array
for ($ctr = 0; $ctr < $num; $ctr++)
{
if (strlen($myarray[$ctr]) > MAXLEN)
{
echo substr($myarray[$ctr], 0, (MAXLEN - 3)) . "...\n";
} else {
echo $myarray[$ctr] . "\n";
}
}
?>
The above will output:
This is a very lo…
short string
some text
some more text to…
This could be used in an instance where we only want to show a predefined “taster”, i.e. replacing … with “(more)” or similar. Alternatively, ensuring that text does not overflow a “<div>” element in a particular instance
Tags: count, PHP, php programmer, strlen, substr
You must be logged in to post a comment.