I have an array of strings. I want to loop through that array and place every 3 characters into another array, eg:
array('abcdefg', 'hij', 'klm');
becomes:
array('abc', 'def', 'hij', 'klm');
I have created the below:
$masterArr = array();
foreach($arr as $i){
array_push($masterArr, (str_split($i,3)));
}
But the str_split
in this creates sub-arrays within $masterArray.
Is there a way I can simply use str_split
to push directly to $masterArray?
You can achieve it by using array_merge() fucntion
$masterArr = array();
foreach($arr as $i){
$masterArr= array_merge($masterArr, str_split($i,3));
// OR if you need only elements which have exact 3 characters then use below line
// $masterArr= array_merge($masterArr, array_filter(str_split($i,3), function($k) {return strlen($k)==3;}));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.