PHP 8 reference · String Functions

PHP str_contains() Function

Check whether a string contains a substring and return true or false. Case-sensitive; added in PHP 8.0.

PHP 8 Since 8.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

str_contains(string $haystack, string $needle): bool

Parameters

ParameterDescription
haystack The string to search in.
needle The string to look for.

Return value

true or false.

Examples

Contains, case-sensitiveTry it yourself
<?php
var_dump(str_contains("ReadyCamel", "Camel"));
var_dump(str_contains("ReadyCamel", "camel"));

Output

bool(true)
bool(false)
Ignore case, empty needleTry it yourself
<?php
$agent = "Mozilla/5.0 (Android 14)";
echo str_contains(strtolower($agent), "android") ? "Android" : "other", "\n";
var_dump(str_contains("abc", "")); // an empty needle is always found

Output

Android
bool(true)

Before PHP 8.0 the usual check was strpos($haystack, $needle) !== false. str_contains() says the same thing clearly and avoids the position-0 trap.

Version history

VersionChange
PHP 8.0Added

In other languages

Was this page helpful?