PHP 8.6.0 Alpha 2 available for testing

Voting

: min(zero, three)?
(Example: nine)

The Note You're Voting On

bishop
22 years ago
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
 echo "found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:
<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
 if ($ignoreCase) {
 $haystack = strtolower($haystack);
 $needle = strtolower($needle);
 }
 $needlePos = strpos($haystack, $needle);
 return ($needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
 echo "Found it";
}
// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
 echo 'Found it at position ' . ($needlePos-1);
}
// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
 echo 'Found it at position ' . ($needlePos-1);
}
?>

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /