-2

I am Considering this PHP string: $stringTest = “this is a sequence of chars”. Let's say I want to have a new string $firstChar that shall contain the first character in $stringTest.

How do I write the program?

vascowhite
  • 18,120
  • 9
  • 61
  • 77
Jabir
  • 41
  • 1
  • 2
  • 8
  • 7
    There was no need to make a question for this there are a thousand places explaining how to do it. Here is one of them http://stackoverflow.com/questions/1972100/getting-the-first-character-of-a-string-with-str0 – Maantje May 20 '16 at 21:02

2 Answers2

1

Just do

$firstChar = $stringTest[0];

Strings are an Array of Chars and therefore can be accessed with an Array Index.

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
1

$firstChar = $stringTest[0];

This would get the first character of string - treating stringTest as an array of characters - and is fastest method.

$firstChar = substr($stringTest, 0, 1);

This is slower, and takes a substring - retrieving 1 character (the last argument) from the string, and setting off from an offset of 0.

Mantis Support
  • 344
  • 2
  • 6