4
I'll Be Writing PHP Functions In Here Just For Fun!
source link: https://dev.to/shoaiyb/php-for-fun-2kc9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
STR_SPRINTF
An alternative to the default function sprintf
<?php
function _sprintf(string $format, mixed ...$values): string {
foreach($values as $key => $value) {
$format = str_replace('%' . $key, $value, $format);
}
return $format;
}
?>
Enter fullscreen modeExit fullscreen mode
Example:
<?php
echo _sprintf('I am %0 and so %1 now!', 'tired', 'hungry'); // returns: I am tired and so hungry now!
?>
Enter fullscreen modeExit fullscreen mode
_SEARCH
What I use to add search functionality to my php sites!
<?php
function _search(string $search, array $in): array|string {
$_search = strtolower($search);
foreach($in as $key => $value) {
$_value = strtolower($value);
if(str_contains($_value, $_search)) {
$result[$key] = $value;
}
}
if(isset($result) && is_array($result)) {
return $result;
} else {
return 'Ohh no! No search result have been found!';
}
}
?>
Enter fullscreen modeExit fullscreen mode
Example:
<?php
print_r(_search('Old', ['New Post', 'Old Post', 'New Page', 'Old Page']));
?>
Enter fullscreen modeExit fullscreen mode
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK