Считать строку массива php

Converting array to string and then back in PHP

How can I convert this array into a string in PHP and back from string into an array. This is kind of a requirement. Could someone please advice on how this can be acheived.

4 Answers 4

You can convert any PHP data-type but resources into a string by serializing it:

And back into it’s original form by unserializing it again:

A serialized array is in string form. It can be converted into an array again by unserializing it.

The same does work with json_encode / — _decode for your array as well:

$string = json_encode($array); $array = json_decode($string); 

Note the difference between using serialize/unserialize vs imlpode/explode is that the former will work regardless of the contents of the values — with the example provided by Alex, the method will fail if one of the valuse contains a space

use the function implode(separator,array) which return a string from the elements of an array.

and then the function explode ( string $delimiter , string $string [, int $limit ] ) to revert it back to an array

$array_as_string = implode(" ",$userarray); $new_array = explode(" ",$array_as_string); 
$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL); $string = json_encode($userarray); $backtoarray = json_decode($string); 
$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL); $string = serialize($userarray); $backtoarray = unserialize($string); 

The first one uses XML storage, and the second uses JSON.

Источник

str_split

Если указан необязательный параметр length , возвращаемый массив будет разбит на фрагменты, каждый из которых будет иметь длину length , за исключением последнего фрагмента, который может быть короче, если строка делится неравномерно. По умолчанию параметр length равен 1 , то есть размер каждого фрагмента будет один байт.

Ошибки

Если параметр length меньше 1 , будет выброшена ошибка ValueError .

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

Версия Описание
8.2.0 Если параметр string не задан, теперь возвращается пустой массив ( array ). Ранее возвращался массив ( array ), содержащий одну пустую строку
8.0.0 Теперь если параметр length меньше 1 , будет выброшена ошибка ValueError ; ранее, вместо этого выдавалась ошибка уровня E_WARNING , а функция возвращала false .

Примеры

Пример #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() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках. Используйте функцию mb_str_split() , чтобы разбить строку на кодовые точки.

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

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

User Contributed Notes 3 notes

The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.

$array = str_split_word_aware (
‘In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.’ ,
32
);

/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array
*/
function str_split_word_aware ( string $string , int $maxLengthOfLine ): array
if ( $maxLengthOfLine <= 0 ) throw new RuntimeException ( sprintf ( 'The function %s() must have a max length of line at least greater than one' , __FUNCTION__ ));
>

$lines = [];
$words = explode ( ‘ ‘ , $string );

$currentLine = » ;
$lineAccumulator = » ;
foreach ( $words as $currentWord )

$currentWordWithSpace = sprintf ( ‘%s ‘ , $currentWord );
$lineAccumulator .= $currentWordWithSpace ;
if ( strlen ( $lineAccumulator ) < $maxLengthOfLine ) $currentLine = $lineAccumulator ;
continue;
>

// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>

if ( $currentLine !== » ) $lines [] = $currentLine ;
>

array( 5 ) [ 0 ]=> string ( 29 ) «In the beginning God created »
[ 1 ]=> string ( 30 ) «the heaven and the earth. And »
[ 2 ]=> string ( 28 ) «the earth was without form, »
[ 3 ]=> string ( 27 ) «and void; and darkness was »
[ 4 ]=> string ( 27 ) «upon the face of the deep. »
>

Источник

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.

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

Источник

Читайте также:  Upload com curl php
Оцените статью