Функция строку в массив php

implode

Alternative signature (not supported with named arguments):

Legacy signature (deprecated as of PHP 7.4.0, removed as of PHP 8.0.0):

Join array elements with a separator string.

Parameters

Optional. Defaults to an empty string.

The array of strings to implode.

Return Values

Returns a string containing a string representation of all the array elements in the same order, with the separator string between each element.

Changelog

Version Description
8.0.0 Passing the separator after the array is no longer supported.
7.4.0 Passing the separator after the array (i.e. using the legacy signature) has been deprecated.

Examples

Example #1 implode() example

$array = [ ‘lastname’ , ’email’ , ‘phone’ ];
var_dump ( implode ( «,» , $array )); // string(20) «lastname,email,phone»

// Empty string when using an empty array:
var_dump ( implode ( ‘hello’ , [])); // string(0) «»

// The separator is optional:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»

Notes

Note: This function is binary-safe.

See Also

  • explode() — Split a string by a string
  • preg_split() — Split string by a regular expression
  • http_build_query() — Generate URL-encoded query string

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.

Читайте также:  My HTML Document

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 );
?>

Читайте также:  Python мыслить как ученый

$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

Источник

explode

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .

Parameters

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .

If the limit parameter is negative, all components except the last — limit are returned.

If the limit parameter is zero, then this is treated as 1.

Note:

Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.

Return Values

Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .

If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.

Changelog

Version Description
8.0.0 explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead.

Examples

Example #1 explode() examples

// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2

// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *

Example #2 explode() return examples

/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );

Читайте также:  Html url from parameter

The above example will output:

array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )

Example #3 limit parameter examples

// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));

// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>

The above example will output:

Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )

Notes

Note: This function is binary-safe.

See Also

  • preg_split() — Split string by a regular expression
  • str_split() — Convert a string to an array
  • mb_split() — Split multibyte string using regular expression
  • str_word_count() — Return information about words used in a string
  • strtok() — Tokenize string
  • implode() — Join array elements with a string

User Contributed Notes 3 notes

Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.

For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:

$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );

Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!

var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >

var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >

If you want to directly take a specific value without having to store it in another variable, you can implement the following:

echo $status_only = explode(‘-‘, $status)[0];

Источник

str_split

Если указан необязательный аргумент split_length , возвращаемый массив будет содержать части исходной строки длиной split_length каждая, иначе каждый элемент будет содержать один символ.

Если split_length меньше 1, возвращается FALSE . Если split_length больше длины строки string , то вся строка будет возвращена в первом и единственном элементе массива.

Примеры

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

$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );

print_r ( $arr1 );
print_r ( $arr2 );

Результат выполнения данного примера:

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

Примечания

Замечание:

Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках.

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

  • chunk_split() — Разбивает строку на фрагменты
  • preg_split() — Разбивает строку по регулярному выражению
  • explode() — Разбивает строку с помощью разделителя
  • count_chars() — Возвращает информацию о символах, входящих в строку
  • str_word_count() — Возвращает информацию о словах, входящих в строку
  • for

Источник

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