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

To find the first index of a substring in a string in PHP, you can use the strpos function. strpos returns the position of the first occurrence of a substring in a string, or false if the substring is not found. Here's an example:

main.php
$string = "The quick brown fox jumps over the lazy dog";
$substring = "brown";

$index = strpos($string, $substring);
if ($index !== false) {
  echo "The substring '$substring' was found at index $index";
} else {
  echo "The substring '$substring' was not found in the string";
}
281 chars
10 lines

In this example, we first define a string $string and a substring $substring. We then use strpos to search for $substring within $string, and store the result in $index. If $substring is found in $string, $index will be set to the index of the first occurrence of $substring (in this case, 10). If $substring is not found in $string, $index will be set to false. We then check if $index is not equal to false, and if so, print out a message saying that $substring was found at $index. If $index is false, we print out a message saying that $substring was not found in $string.

gistlibby LogSnag