Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine strings inside foreach into single string PHP

I have code like this

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

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

The output was

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

For some reasons, I want to make the output become only 1 string like this:

string(3) "foo"

I tried with this

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

But it shows error Undefined variable: char.

like image 510
Wakanina Avatar asked Dec 13 '12 14:12

Wakanina


People also ask

How can I combine two strings together in PHP?

There are two string operators. The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.

Can we use foreach inside foreach?

Due to operator precedence, you cannot put braces around the inner foreach loop. This is structured very much like the nested for loop. The outer foreach is iterating over the values in bvec , passing them to the inner foreach , which iterates over the values in avec for each value of bvec .

What is concatenate in PHP?

1. Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.

Can we use for loop inside foreach loop in PHP?

We can also use a for loop inside another for loop. Here is a simple example of nested for loops.


1 Answers

I'm going to assume that you have a good reason for splitting it up, only to put it back together again:

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

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

echo var_dump($result);

Which outputs the following:

string(3) "foo"
like image 175
Sampson Avatar answered Nov 10 '22 03:11

Sampson