

Дата публикации: 19.12.2024
How to apply the rtrim function to each element of an array
In PHP, if you want to apply the rtrim
function to each element of an array, you can use the array_map
function. The rtrim
function is used to strip whitespace (or other characters) from the end of a string.
Here's an example of how to use array_map
with rtrim
:
<?php
// Sample array with strings
$array = ["Hello ", "World ", "PHP ", " DuckDuckGo "];
// Use array_map to apply rtrim to each element
$trimmedArray = array_map('rtrim', $array);
// Print the result
print_r($trimmedArray);
?>
Explanation:
- The
array_map
function takes two arguments: the first is the callback function (in this case,rtrim
), and the second is the array you want to process. rtrim
is applied to each element of the array, and the result is stored in$trimmedArray
.- Finally,
print_r
is used to display the trimmed array.
Output:
The output of the above code will be:
Array
(
[0] => Hello
[1] => World
[2] => PHP
[3] => DuckDuckGo
)
As you can see, the whitespace at the end of each string has been removed, except for the last element, which still has leading whitespace. If you want to trim both sides, you can use trim
instead of rtrim
.