find the first index of a character in a string in php

To find the first index of a character in a string in PHP, you can use the strpos() function.

Here's an example code:

main.php
$string = "Hello World";
$char = "o";
$pos = strpos($string, $char);

if ($pos === false) {
  echo "The character '$char' was not found in the string '$string'";
} else {
  echo "The first occurrence of the character '$char' in the string '$string' is at position $pos";
}
273 chars
10 lines

In this example, we're searching for the character "o" in the string "Hello World". The strpos() function returns the position of the first occurrence of the character, or false if the character is not found.

Note that we're using the === operator to check if the value returned by strpos() is false. This is because strpos() may return 0, which is an integer and evaluates to false in a regular comparison. The === operator checks both the value and the data type, so it will only return true if the value is actually false.

gistlibby LogSnag