How to combine strings inside foreach into single string PHP

后端 未结 8 1373
傲寒
傲寒 2020-12-11 04:35

I have code like this

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

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

The out

相关标签:
8条回答
  • 2020-12-11 05:07

    I would just use implode, much like this: $string = implode('', $char_buff);

    0 讨论(0)
  • 2020-12-11 05:13

    Sounds like you are looking for implode() http://php.net/manual/en/function.implode.php

    As for the code you posted $chars .= $char; is probably what you were trying to do

    0 讨论(0)
  • 2020-12-11 05:16

    So, why do you split it just to make it a string again?

    $word='foo'
    $char_buff = str_split($word);
    
    $final = array();
    foreach ($char_buff as $chars){
        $final[] = $chars;
    }
    
    var_dump( implode('', $final) );
    
    0 讨论(0)
  • 2020-12-11 05:18

    str_split() converts a string to an array. There's no need to use this function if you want to keep the whole word.

    0 讨论(0)
  • 2020-12-11 05:23
    <?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);
    }
    ?>
    
    0 讨论(0)
  • 2020-12-11 05:23

    Maybe some of you are looking for this answer. I think var_dump() is no longer necessary for this problem.

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

    Here is the 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>

    0 讨论(0)
提交回复
热议问题