Php объединить массив строку

PHP implode

Summary: in this tutorial, you’ll learn how to use the PHP implode() function to join a list of string using a separator.

Introduction to the PHP implode() function

The PHP implode() function allows you to join an array of strings by a separator. Here’s the syntax of the implode() function:

implode ( string $separator , array $array ) : stringCode language: PHP (php)

The implode() function has two parameters:

  • The $separator is the separator that separates between two strings. The $separator defaults to an empty string.
  • The $array is an array of strings to join.

The implode() function returns a new string resulting from joining string elements in the $array with the separator.

The order of string elements in the result string is the same as the order they appear on the $array.

If the array is empty, then the implode() function returns an empty string.

Note that the join() function is the alias of the implode() function so that you can use them interchangeably.

Читайте также:  Web forum php bb

PHP implode() function examples

Let’s take some examples of using the implode() function.

1) Using the implode() function to join strings example

Suppose that you have a list of column names, including first_name, last_name, and email. And you want to turn it into a header of a CSV file.

To do that, you can use the implode() function to join the string elements like this:

 $columns = ['first_name', 'last_name', 'email']; $header = implode(',', $columns); echo $header;Code language: PHP (php)
first_name,last_name,emailCode language: PHP (php)

2) Using the implode() function with the array_map() function

If you want to replace the underscore (_) in each element, you can do it as follows:

 $columns = ['first_name', 'last_name', 'email']; $header = implode(',', array_map(fn ($c) => str_replace('_', ' ', $c), $columns)); echo $header;Code language: PHP (php)
  • First, the array_map() returns a new array with each element’s underscore string ( _ ) replaced by the space.
  • Second, the implode() joins the strings of the returned array of the array_map() function.

3) Using the implode() function with the array_filter() function

The following example illustrates how to use the implode() function with the array_filter() function:

 $columns = ['ssn', 'first_name', 'last_name', 'password', 'email', 'phone']; $excludes = ['ssn', 'password']; $header = implode(',', array_filter($columns, fn ($c) => !in_array($c, $excludes))); echo $header;Code language: PHP (php)
first_name,last_name,email,phoneCode language: PHP (php)
  • First, define two arrays of strings, one for columns and the other for excluding columns.
  • Second, use the array_filter() function to filter the columns in the excluded list.
  • Third, use the implode() function to join the strings in the array returned by the array_filter() function.

4) Using the PHP implode() function with an associative array example

If you pass an associative array to the implode() function, it will join the array’s values only and disregard the array keys. For example:

 $person = [ 'first_name' => 'John', 'last_name' => 'Doe', 25, 'Female' ]; echo implode(',', $person);Code language: PHP (php)
John,Doe,25,FemaleCode language: PHP (php)

5) Using the PHP implode() function with an array that has one element

The following defines a function called get_header() that returns a comma-separated list of columns:

 function get_header(array $columns): string < if (1 === count($columns)) < return $columns[0]; > return implode(',', $columns); >Code language: PHP (php)

The get_header() function returns the first element in the $columns array if the $columns array has one element. Otherwise, it returns a comma-separated list of strings in the $columns array.

The following shows how to use the get_header() function:

 echo get_header(['first_name']); // first_name echo get_header(['first_name', 'last_name']); // first_name,last_nameCode language: PHP (php)

However, the code in the get_header() is unnecessary since the implode() function already has a logic to handle the array with one element. For example:

 echo implode(',', ['first_name']); // first_name echo implode(',', ['first_name', 'last_name']); // first_name,last_nameCode language: PHP (php)

When the input array has one element, the implode() function doesn’t add a trailing separator, which is the comma in this example.

Summary

  • Use the PHP implode() function to join strings in an array with a separator between each element.

Источник

implode

Альтернативная сигнатура (не поддерживается с именованными аргументами):

Устаревшая сигнатура (устарела с PHP 7.4.0, удалена в PHP 8.0.0):

Объединяет элементы массива с помощью строки separator .

Список параметров

Необязательный. По умолчанию равен пустой строке.

Массив объединяемых строк.

Возвращаемые значения

Возвращает строку, содержащую строковое представление всех элементов массива в указанном порядке, с разделителем между каждым элементом.

Список изменений

Версия Описание
8.0.0 Передача separator после array больше не поддерживается.
7.4.0 Передача separator после array (т.е. использование недокументированного порядка параметров) устарела.

Примеры

Пример #1 Пример использования implode()

$array = [ ‘имя’ , ‘почта’ , ‘телефон’ ];
var_dump ( implode ( «,» , $array )); // string(32) «имя,почта,телефон»

// Пустая строка при использовании пустого массива:
var_dump ( implode ( ‘привет’ , [])); // string(0) «»

// Параметр separator не обязателен:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • explode() — Разбивает строку с помощью разделителя
  • preg_split() — Разбивает строку по регулярному выражению
  • http_build_query() — Генерирует URL-кодированную строку запроса

User Contributed Notes 14 notes

it should be noted that an array with one or no elements works fine. for example:

$a1 = array( «1» , «2» , «3» );
$a2 = array( «a» );
$a3 = array();

echo «a1 is: ‘» . implode ( «‘,'» , $a1 ). «‘
» ;
echo «a2 is: ‘» . implode ( «‘,'» , $a2 ). «‘
» ;
echo «a3 is: ‘» . implode ( «‘,'» , $a3 ). «‘
» ;
?>

will produce:
===========
a1 is: ‘1’,’2′,’3′
a2 is: ‘a’
a3 is: »

It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:

$a = array( ‘one’ , ‘two’ , ‘three’ );
$b = array( ‘1st’ => ‘four’ , ‘five’ , ‘3rd’ => ‘six’ );

echo implode ( ‘,’ , $a ), ‘/’ , implode ( ‘,’ , $b );
?>

outputs:
one,two,three/four,five,six

Can also be used for building tags or complex lists, like the following:

?>

This is just an example, you can create a lot more just finding the right glue! 😉

It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.

class Foo
protected $title ;

public function __construct ( $title )
$this -> title = $title ;
>

public function __toString ()
return $this -> title ;
>
>

$array = [
new Foo ( ‘foo’ ),
new Foo ( ‘bar’ ),
new Foo ( ‘qux’ )
];

echo implode ( ‘; ‘ , $array );
?>

will output:

If you want to implode an array of booleans, you will get a strange result:
var_dump ( implode ( » ,array( true , true , false , false , true )));
?>

Output:
string(3) «111»

TRUE became «1», FALSE became nothing.

If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.

function mapped_implode ( $glue , $array , $symbol = ‘=’ ) return implode ( $glue , array_map (
function( $k , $v ) use( $symbol ) <
return $k . $symbol . $v ;
>,
array_keys ( $array ),
array_values ( $array )
)
);
>

echo mapped_implode ( ‘, ‘ , $arr , ‘ is ‘ );

// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo

Sometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.

function wrap_implode ( $array , $before = » , $after = » , $separator = » ) if( ! $array ) return » ;
return $before . implode ( » < $after >< $separator > < $before >» , $array ) . $after ;
>

echo wrap_implode ([ ‘path’ , ‘to’ , ‘file.php’ ], ‘/’ );
// «/path/to/file.php»

$pattern = ‘#’ . wrap_implode ([ 4 , 2 , 2 ], ‘\d’ , ‘[-.]’ ) . ‘#’ ;
echo $pattern , «\n» ; // #\d[-.]\d[-.]\d#
echo preg_replace ( $pattern , ‘[REDACTED]’ , ‘The UFO appeared between 2012-12-24 and 2013.01.06 every night.’ );
// ‘The UFO appeared between [REDACTED] and [REDACTED] every night.

echo wrap_implode ([ ‘line’ , ‘by’ , ‘line’ ], ‘‘ , ‘‘ , ‘
‘ );
// line
by
line

It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
var_dump ( implode ( ‘:’ , ‘xxxxx’ ));
?>
returns
NULL

This threw me for a little while.

Even handier if you use the following:

$id_nums = array( 1 , 6 , 12 , 18 , 24 );

$id_nums = implode ( «, » , $id_nums );

$sqlquery = «Select name,email,phone from usertable where user_id IN ( $id_nums )» ;

// $sqlquery becomes «Select name,email,phone from usertable where user_id IN (1,6,12,18,24)»
?>

Be sure to escape/sanitize/use prepared statements if you get the ids from users.

null values are imploded too. You can use array_filter() to sort out null values.

$ar = array( «hello» , null , «world» );
print( implode ( ‘,’ , $ar )); // hello,,world
print( implode ( ‘,’ , array_filter ( $ar , function( $v )< return $v !== null ; >))); // hello,world
?>

If you want to use a key inside array:

Example:
$arr=array(
array(«id» => 1,»name» => «Test1»),
array(«id» => 2,»name» => «Test2»),
);

echo implode_key(«,»,$arr, «name»);
OUTPUT: Test1, Test2

function implode_key($glue, $arr, $key) $arr2=array();
foreach($arr as $f) if(!isset($f[$key])) continue;
$arr2[]=$f[$key];
>
return implode($glue, $arr2);
>

It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.

$test = implode ([ «one» , 2 , 3 , «four» , 5.67 ]);
echo $test ;
//outputs: «one23four5.67»
?>

There is no mention of behavior on a empty array, so I tried it and here’s the result:

$ar = array();
$result = implode ( ‘,’ , $ar ); // Comma arbitrarily applied as the separator
$is_result_empty = empty( $result );
?>

$result:
$is_result_empty: 1

In other words, an empty string is the result.

* Join pieces with a string recursively .
*
* @ param mixed $glue String between pairs ( glue ) or an array pair ‘s glue and key/value glue or $pieces.
* @param iterable $pieces Pieces to implode (optional).
* @return string Joined string
*/
function double_implode($glue, iterable $pieces = null): string
$glue2 = null;
if ($pieces === null) $pieces = $glue;
$glue = »;
> elseif (is_array($glue)) list($glue, $glue2) = $glue;
>

$result = [];
foreach ($pieces as $key => $value) $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
>
return implode($glue, $result);
>
?>
Examples:
$array = [‘ a ‘ => 1, ‘b’ => 2];
$str = implode($array);
$str = implode(‘ , ‘, $array);
$str = implode([‘» ‘, ‘ keyword»>, ‘, $iterator);
$str = implode([‘» ‘, ‘ foot»>+add a note

Источник

PHP implode() Function

In this article, you will learn about how to convert the array into a string in PHP. The implode() function converts the array into a string or in other words, it returns a string by joining the elements of the array.

Implode() function is an alias of the join() function. Also, it accepts the parameters in both lefts to right/right to left order. However, they are passed in the order of convention (like explode() function).

You can also specify the separator character but it is not mandatory. However, for backward compatibility, you must use the two arguments.

This function is binary-safe. Binary safe functions are those, that produce the same output even if there are some special characters present in the string. Their output is not disturbed by the special chars.

WHAT IS THE SYNTAX OF THE JOIN() FUNCTION IN PHP?

Parameters Details
separator It specifies the character or string to place between two array elements while joining them – Optional – Default value is empty string or “”
array The array to consider to convert to string

PHP implode() method

EXAMPLES OF THE implode() FUNCTION

Example 1. In this example, we take an array with some string elements in it. We created a string by joining all the strings of the array.

Example 2. In this example, we join the array by using different separator characters.

Источник

Оцените статью