Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: implode('\n', $appArray) generates extra '\'

Tags:

php

I have the following array

$appArray=array('a', 'b', 'c');

I want to produce output such as 'a\nb\nc\n'. The trouble is that when I use

implode('\n', $appArray)

I get 'a\\nb\\nc\\n' ( note the extra backslash).

Any idea how to fix this?

like image 662
Graviton Avatar asked Sep 26 '09 06:09

Graviton


People also ask

What does PHP implode do?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.

What would implode explode string )) do?

As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter.

What is implode in laravel?

The implode method will help to generate string using glue with given argument key. I will give you simple example of implode() colletion in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9 application.08-Oct-2020.


3 Answers

Are you sure you're not intending: implode("\n", $appArray)? Newline characters aren't actually treated as newline characters when encapsulated in 'single quotes'.

like image 154
brianreavis Avatar answered Oct 29 '22 04:10

brianreavis


Use PHP_EOL (end of line) :

implode(PHP_EOL, $array);
like image 42
Adi Avatar answered Oct 29 '22 05:10

Adi


Actually, in single quotes \n means \n (literally), not carriage return. Try using double quotes in implode ().

like image 3
Ilya Birman Avatar answered Oct 29 '22 03:10

Ilya Birman