How to use array_filter() and strlen() Functions In PHP

The array_filter() function can be utilized along with a custom callback function to filter out the words with an even length.

PHP




<?php
  
function isEvenLength($word) {
    return strlen($word) % 2 === 0;
}
  
function EvenLengthWords($str) {
      
    // Split the string into an
    // array of words
    $words = explode(' ', $str);
  
    // Use array_filter to keep only 
    // even-length words
    $evenLengthWords = array_filter($words, 'isEvenLength');
  
    // Print the even-length words
    echo implode(' ', $evenLengthWords);
}
  
// Driver code
$str = "Welcome to Geeks for Geeks, A computer science portal";
  
EvenLengthWords($str);
  
?>


Output

to Geeks, computer portal

PHP Program to Print Even Length Words in a String

This article will show you how to print even-length words in a string using PHP. Printing even-length words from a given string is a common task that can be approached in several ways.

Table of Content

  • Using explode() and foreach() Functions
  • Using array_filter() and strlen() Functions
  • Using preg_split() and array_filter() Functions

Similar Reads

Using explode() and foreach() Functions

The explode() function can be used to split the string into an array of words, and then a foreach loop can be employed to filter and print the words with an even length....

Using array_filter() and strlen() Functions

...

Using preg_split() and array_filter() Functions

The array_filter() function can be utilized along with a custom callback function to filter out the words with an even length....