8

我有这样的代码

$word = 'foo';
$char_buff = str_split($word);

foreach ($char_buff as $chars){
    echo var_dump($chars);
}

输出是

string(1) "f" 
string(1) "o" 
string(1) "o"

由于某些原因,我想让输出变成这样的只有 1 个字符串:

string(3) "foo"

我试过这个

$char.=$chars;
echo var_dump($char);

但它显示错误Undefined variable: char

4

8 回答 8

15

我将假设您有充分的理由将其拆分,只是将其重新组合在一起:

$word = 'foo';
$result = "";
$char_buff = str_split($word);

foreach ($char_buff as $char){
    $result .= $char;
}

echo var_dump($result);

输出以下内容:

string(3) "foo"
于 2012-12-13T14:40:31.167 回答
2

str_split()将字符串转换为数组。如果要保留整个单词,则无需使用此功能。

于 2012-12-13T14:40:51.543 回答
2

我只会使用内爆,就像这样: $string = implode('', $char_buff);

于 2012-12-13T14:47:13.260 回答
1

那么,为什么要拆分它只是为了让它再次成为一个字符串?

$word='foo'
$char_buff = str_split($word);

$final = array();
foreach ($char_buff as $chars){
    $final[] = $chars;
}

var_dump( implode('', $final) );
于 2012-12-13T14:40:59.030 回答
0

听起来你正在寻找 implode() http://php.net/manual/en/function.implode.php

至于您发布的代码 $chars .= $char; 可能是你想要做的

于 2012-12-13T14:40:39.827 回答
0

拆分字符串,然后再次将其粘合在一起有点奇怪,但这里是:

$word='foo'
$char_buff = str_split($word);

// this is what is missing, you have to define a variable first
$newword = "";

foreach ($char_buff as $chars){
     $newword .= $chars;
}

echo var_dump($newword);
于 2012-12-13T14:41:36.860 回答
0
<?php
$word = 'foo';
$char_buff = str_split($word);

// here is the trick
$length = count($char_buff);
$char_buff[$length] = $word;

foreach ($char_buff as $chars)
{
    echo var_dump($chars);
}
?>
于 2012-12-13T14:48:40.257 回答
0

也许你们中的一些人正在寻找这个答案。我认为这个问题不再需要 var_dump() 。

<?php 
    if(isset($_POST['test'])){
        $result = '';
        for($x=1;$x<=4;$x++){
            $ans = $_POST['ans'.$x];
            $result .= $ans;
        } 
    echo $result; 
    }
?>

这是HTML

<form role="form" method="post" action="<?php echo $url;?>">
	<input type="checkbox" name="ans1" value="A">A 
	<input type="checkbox" name="ans2" value="B">B 
	<input type="checkbox" name="ans3" value="C">C 
	<input type="checkbox" name="ans4" value="D">D 
	<input type="submit" name="test" value="Submit Answer">
</form>

于 2017-11-18T04:59:56.693 回答