Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What are PHP 8 string-related functions?

Abel Lifaefi Mbula

Overview

PHP 8 was released in November 2020 and brought out a lot of new features and performance improvements. Let's learn some string-related functions available in PHP 8.

The str_contains() function

PHP 8 proposes a new basic function, str_contains(), that checks if a string is contained in another string and returns a boolean value whether or not the string was found. The syntax looks like this:

<?php
str_contains ( string $haystack, string $needle ) : bool;
str_contains function

The function takes two parameters, $haystack and $needle, and checks if the second parameter is found in the first one and returns true or false whether or not the $needle was found. Prior to PHP 8, we had to rely on strpos or ststr functions.

Example

<?php 

function containsStr(string $haystack, string $needle): bool {
    if (str_contains($haystack, $needle)) {
        return true;
    }
}
 
var_dump(containsStr('I learn on studytonight', 'studytonight'));

The str_starts_with() function

PHP 8 comes with this new string-related function that checks if a given haystack string starts with the given needle string. The syntax looks almost the same as in str_contains():

<?php

str_starts_with ( string $haystack, string $needle ) : bool;

Example

<?php

var_dump(str_starts_with('studytonight is so good', 'studytonight'));

The str_ends_with() function

Like the previous function, this function checks if a given haystack string ends with the given needle string. Here’s an example:

Example

<?php

var_dump(str_ends_with('I learn on studytonight', 'studytonight'));
str_ends_with

The fdiv() function

PHP 8’s new fdiv() function fits along functions such as fmod() and intdiv() which allow for division by 0. Instead of errors, it returns INF, -INF or NAN depending on the case.

Example

<?php

fdiv(1, 0); // float(INF)

fdiv(-1, 0); // float(-INF)
fdiv function

Summary

Let's recap.

  • str_contains(): A boolean function that checks if a string is contained in another one.
  • str_starts_with(): Another boolean function that checks if a string starts with a given string.
  • str_ends_with(): A boolean function that checks if a string ends with the given string.
  • fdiv(): Used for division by 0.

RELATED TAGS

php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring