String parsing by character in PHP without foreach -
i next conversion in php:
from: "0110001" to: "tuesdays, wednesdays, sundays".
bonus points doing one:
from: "0110001" to: "tuesdays, wednesdays , sundays".
the input 7 characters, each represents day of week.
how can without foreach loop? utilize array_walk or array_reduce.
working solution foreach :
<?php function parsedays($str) { $days = array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"); $result = array(); foreach (str_split($str) $k=>$v) { if ($v == '1') { $result[] = $days[$k]; } } homecoming join(', ', $result); } echo parsedays("0110001");
you can first version built-in functions:
$daynames = array( 'mondays', 'tuesdays', // etc ); $in = "0110001"; echo implode(', ', array_intersect_key($daynames, array_filter(str_split($in))));
how works:
split input array of ones , zeroes; crucially, keys of array match keys of$daynames
. filter out zeroes; fortunately array_filter
preserves keys. use array_intersect_key
map keys values within $daynames
. use implode
create comma-separated list of above. if want convert lastly comma "and"
, terse way regular look (personally find solution questionable although it's undeniably effective):
echo preg_replace('/,(?=[^,]+$)/', ' and', implode(...));
however please don't forget best kind of code code not exist (guaranteed 0 bugs!), , sec best code understand eyes closed.
the code above not fall either of categories; professional recommendation utilize foreach
if results in code familiar whoever going maintain it.
php string parsing
No comments:
Post a Comment