The Most Active and Friendliest
Affiliate Marketing Community Online!

“AdsEmpire”/  Direct Affiliate

Tip: accessing individual characters of a php string

D

dman_2007

Guest
If you would like to process individual characters of a string in php, you can access them by using following two methods :

Method 1

By using square bracket syntax and zero based offset. So for example, if you want to access second character of a string stored in variable $string_var, then use the expression $char_value = $string_var[2], now $char_value will contain a string 1 character long containing the required character.

PHP:
  $sample_string = 'This is a sample string';
  for($i = 0;$i < strlen($sample_string);$i++)
  {
    var_dump($sample_string[$i]);  
  }

Method 2

By using substr function. We can use substr function to extract 1 character substrings successively within a for loop, hence accessing individual characters in string.

PHP:
  $sample_string = 'This is a sample string';
  for($i = 0;$i < strlen($sample_string);$i++)
  {
    var_dump(substr($sample_string, $i, 1));
  }
 
MI
Back