substr()


today i was breaking my head trying to figure out how i can do this. i had a string called time.. like this:

$time = 1223452828;

now what i wanted to do was to change the value of $time into only the last two digits in the string so i wanted to change it to:

$time = 28;

well, how do you do this. i will teach you, this is how you obtain and show it with print or echo

1. the first step is to declare the value of our string, in my example here it will be 1223452828;

PHP CODE:
$time = 1223452828;
VALUE: 1223452828 ($time)

2. the second step is to determine how many characters our $time string has, so we use the strlen() function in php:
PHP CODE
$length = strlen($time);
VALUE: 10 (length)

3. if you count the number of characters in the $time string(1223452828), is equal to 10 character. so now we the length in characters of our string. now we will declare a new string called $characters. we will use the value of $characters to determine how many characters we want to get from our $time string. in my case, i want the last two characters so im going to give it a value of 2:

PHP CODE:
$characters = 2;
VALUE: 2 ($characters)

4. the next step is to declare a new string called $start. we will use calculate the value of $start by substracting $characters from $length (10 - 2 = 8)

PHP CODE
$start = $length - $characters;
VALUE: 8 ($start)

5. ok, now that we have all the three critical values to the substr() function. we can use it to get the last two digits from our $time string:

PHP CODE
$time = substr($time , $start ,$characters);
VALUE: 2 ($time)

6. now we have changed the value of $time from 1223452828 to 28. here is the whole code/snippet:

PHP CODE

$time = 1223539228;
$length = strlen($time);
$characters = 2;
$start = $length - $characters;
$time = substr($time , $start ,$characters);
echo $time;

OUTPUT: 28

i hope this helps