In PHP, strpos()
is a built-in function used to find the position of the first occurrence of a substring inside another string.
🔹 Syntax:
strpos(string $haystack, mixed $needle, int $offset = 0): int|false
- $haystack: The main string you want to search in.
- $needle: The substring you're looking for.
- $offset (optional): Start searching from this position.
- Returns:
- The position (0-based index) of the first occurrence of
$needle
. false
if$needle
is not found.
- The position (0-based index) of the first occurrence of
✅ Basic Example:
<?php
$text = "Hello, world!";
$pos = strpos($text, "world");
if ($pos !== false) {
echo "Found at position: $pos"; // Output: Found at position: 7
} else {
echo "Not found";
}
?>
Notice:
===
is used instead of==
to strictly check forfalse
(since position0
is valid).
🔍 Example with Offset:
<?php
$text = "I love PHP. PHP is great!";
$pos = strpos($text, "PHP", 10);
echo $pos; // Output: 15 (the second occurrence)
?>
❌ Not Found Example:
<?php
$text = "Learning Laravel!";
$pos = strpos($text, "PHP");
if ($pos === false) {
echo "Not found"; // Output: Not found
}
?>
⚠️ Common Mistake:
$pos = strpos("PHP is cool", "PHP");
if ($pos) {
echo "Found"; // ❌ Won't echo because 0 == false
}
// Always use !== false to avoid this trap!
🎯 Use Case: Check if a string contains another string
function contains($text, $keyword) {
return strpos($text, $keyword) !== false;
}
echo contains("Laravel is awesome", "awesome") ? "Yes" : "No"; // Output: Yes
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.