Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中相同数组的元素组合_Php_Arrays - Fatal编程技术网

PHP中相同数组的元素组合

PHP中相同数组的元素组合,php,arrays,Php,Arrays,在我的项目中,我必须从用户那里接收一个字符串(在textarea中)。现在这个字符串将被转换成数组。现在的问题是,字符长度必须至少为3, 在以下数组中,如果字符长度小于3,则下一个元素应与当前元素联接。如何在PHP中执行它 a[0]=>this a[1]=>is a[2]=>an a[3]=>example a[4]=>array. 输出应为: a[0]=>this a[1]=>isan a[2]=>example a[3]=>array.

在我的项目中,我必须从用户那里接收一个字符串(在textarea中)。现在这个
字符串
将被转换成
数组
。现在的问题是,字符长度必须至少为3, 在以下数组中,如果字符长度小于3,则下一个元素应与当前元素联接。如何在
PHP
中执行它

a[0]=>this a[1]=>is a[2]=>an a[3]=>example a[4]=>array.
输出应为:

a[0]=>this a[1]=>isan a[2]=>example a[3]=>array.
试一下:

$input  = ['this', 'is', 'an', 'example', 'array.'];
$output = [];

$part = '';
foreach ($input as $value) {
    $part .= $value;
    if (strlen($part) > 3) {
        $output[] = $part;
        $part = '';
    }
}
输出:

array (size=4)
  0 => string 'this' (length=4)
  1 => string 'isan' (length=4)
  2 => string 'example' (length=7)
  3 => string 'array.' (length=6)

[1]=>是一个[2]=>a
如何给出
[1]=>是一个a
,为什么要合并这些元素?感谢hsz提供所需的解决方案。@ImranKhanMicro记住接受答案并在左边打勾。