If you need to convert a php array to a string, then there are several tools for this. The use of this or that tool depends on your goals.

1. The implode () function

With its help, you can "glue" array elements into a string, through any separator. Read more: implode
Example:

Echo implode ("|", array (1, 2, 3)); // will output the line: 1 | 2 | 3

This function has an antagonist explode (), which, on the contrary, splits the string by separator into array elements. Read more: explode

2. The serialize () function

The main task of the function is to transform a variable (in our case, an array) into a state suitable for storage.
It is used to store an array into a string, for later converting it back to an array. You can save the array to a file or database, and then restore it the next time the script is executed.
Read more: serialize

$ array = array ("1" =>; "elem 1", "2" => "elem 2", "3" => "elem 3"); $ string = serialize ($ array); echo $ string; // will output a string: a: 3: (i: 1; s: 6: "elem 1"; i: 2; s: 6: "elem 2"; i: 3; s: 7: "elem 3";)

Then, from this line, you can get the array again:

$ array = unserialize ($ string);

3. Function json_encode ()

Returns a JSON representation of the data. You can read what it is.
In our case, this function resembles serialization, but JSON is mainly used to transfer data. You will have to use this format to communicate with javascript on the frontend. More details: json_encode

$ array = array (1 => "one", 2 => "two",); $ json = json_encode ($ array); echo $ json; // ("1": "one", "2": "two")

The reverse function json_decode () will return an object of type stdClass if the second parameter of the function is false. Or it will return an associative array if you pass true as the second parameter. Details here.

JavaScript is blocked in your browser. Please enable JavaScript for the site to work!

implode

(PHP 3, PHP 4, PHP 5)

implode- Concatenates the elements of an array into a string (converts an array to a string)

Description

string implode(string glue, array pieces)

Returns the string obtained by concatenating the string representations of the pieces in pieces, with the string glue inserted between adjacent elements.

Example 1. Example of use implode ()

Comment: For historical reasons, functions implode () you can pass arguments in any order, however, for unification with the function explode () the documented order of the arguments should be used.

Comment: Since version 4.3.0 the argument to the glue function implode () is optional and defaults to an empty string (""). For backward compatibility, it is recommended to always pass both arguments.

Comment: This function is safe for processing data in binary form.

This function concatenates the values ​​of the array elements into a string. Use the following code to concatenate the keys of the array elements:

php implode for nested arrays

If you pass a multidimensional array to implode, you will get an "Array to string conversion" error. To avoid this error, use the following equivalent to the implode function:

Function multi_implode ($ glue, $ array) ($ _array = array (); foreach ($ array as $ val) $ _array = is_array ($ val)? Multi_implode ($ glue, $ val): $ val; return implode ($ glue, $ _array);)

See also function descriptions

Hello, yesterday you and I studied how you can split a string and get an array from it. Today I bring to your attention the opposite function, with the help of which we can convert array to string... This is called implode function... The principle of operation of this function is similar to the previous one, but we will consider it with an example:

$ array = array ( "My name is Denis") ;
$ string = implode ( "", $ array);
echo $ string;
?>

We have created an array with three elements, and with implode functions turned it into a string. This function can take two parameters. The first one is optional and means which separator will be applied between the elements of the array. If this parameter is not specified, then by default the array elements will be separated by a space. And the second parameter is the array itself, which will be converted to a string. These are all the parameters that the function under study supports. As a result of executing the function, you will receive a string (My name is Denis). If we specified a comma as a separator, the result would be (My name is Denis). I think there were no problems with the study of this function, and you yourself can use it when creating your sites... This concludes this article, as you can see, it was rather small in volume, but very important from the point of view of practice. See you soon, success in learning programming languages!

PHP, as a modern programming language, provides the ability to process data, the type of which can be determined at the time of use. The data type can change during the execution of the program.

Character strings are the only data type to which data of other types is naturally reduced, on the simple reason that any given data is always a sequence of characters.

PHP arrays

In addition to regular variables, PHP provides the programmer with syntax and functions for working with arrays. In addition to ordinary arrays that provide access to their elements by key (a digit from 0 to the number of elements), you can use associative arrays. In the latter, access can be carried out both by a numerical index (assigned by the machine), and by a key specified by the programmer.

PHP provides the ability to swap indexes and values, which makes sense because there is no official requirement for a key than for a value, but you should use this carefully. For a long time, programming traditions have appealed to the letters of the Latin alphabet. Cyrillic, as a general rule, brings with it the problem of encodings. You should not abuse the capabilities of the language when you need practical and safe code.

The best index option is a meaningful phrase in English, preferably without spaces. It's great that PHP's syntax declares "freedom" for keys, but it's better to trust your own experience and focus on secure code.

The most interesting and practical feature of PHP's array-to-string solution is the equivalent reciprocal conversion.

PHP: arrays and strings

The "arrays to string" PHP function: $ cLine = implode ("/", $ aStyle) outputs a character string from all elements of the $ aStyle array, separated by the "/" character. If you specify "", then all elements will be merged into one continuous sequence of characters.

The inverse $ aStyle = explode ("/", $ cLine) creates an array of all lines separated by "/".

When using the explode () function, it is advisable, but not necessary, to check for the correct delimiter character in the original string.

You can also output arrays to a string in PHP in more humane and controlled ways. For example, in a for, while, foreach loop, adding the values ​​of array elements to the string variable using the assignment operator: ". =" Or the operator "." convert strings (process each element).

PHP: output array to string via objects

An object is a collection of data and code. Nothing prevents you from placing, for example, two functions in your code: write and read. Thanks to inheritance and polymorphism, having a circle object, you can have its variations: blue, red and green.

Each will be written (read) in its own way, but how exactly the PHP "arrays to string" solution is executed will not matter. In essence, objects carry a certain meaning, have a different structure and different methods. An example with two functions is a particular. By constructing such a mechanism in PHP, arrays in a string will be placed in each case in its own way.

This opens up great opportunities. One object has two arrays, the other has twenty, and the common ancestor (usually the very first one is abstract) has nothing at all. Using the methods of their common ancestor, you do not have to worry that something will not be written, read, processed or displayed.

Thanks to inheritance, whatever shape is used anywhere in the program, it can be represented as a string and read back into the object of this particular shape.

Converting data from one representation to another is a popular, often the only, mechanism for solving the problem. An array is a simple case of an object. A string is a natural representation of information for transmission, processing, or storage.

Experience and semantics implemented in PHP: arrays, functions and syntactic constructions make it possible to create optimal solutions for processing information in the form in which it is presented.

Information: characters, strings and data

In its "pure" form, information is a string of characters, speech, or a sequence of signals. In programming, strings, arrays and objects appear - these are variants of artificial inline constructions. Numbers are also strings, but numbers, not symbols.

PHP allows you to convert a string to an array in many different ways. There are two special functions that do this on their own:

  • $ aArr = explode ("x", "string");
  • $ aStr = implode ("y", $ aArr).

The first function finds the "x" separator character and splits the "string" along it. The resulting array contains exactly the number of elements (strings) that are contained between the characters "x". The separator symbol may not necessarily be the classic ones:

  • comma;
  • point;
  • semicolon.

You can split a string by substring or by a special combination of characters.

String length is strlen () in PHP, array length is count (). In the first case, the number of characters is considered, in the second case, the number of elements. Since the separator character is not included in the array elements, the count () value will be equal to the number of separators in the converted string minus one.

During PHP reverse transformation, arrays are converted to a string with a separator character (may be empty), and all data (numbers and logical expressions) are merged into one string. An array element can be another array, but the programmer must take special care of this case. The implode () function is far from recursive.

In this example, there is no problem converting PHP arrays to a string as long as there is no other array among their elements. When converting associative elements, key information is lost. In particular, the elements "plum" and "peach" will be deprived of their keys.

Data delimiters and keys

Do not consider periods, commas, colons, etc. as separators. This is a special case of separating data from each other. When transforming a string in PHP, a multidimensional array will not work, and associative indices will have nowhere to come from.

When parsing a string by separator, you always get strings. But this is not a reason to stop there. Having parsed one line into its constituent elements, you can go further.

For example, there was a paragraph, it contains several sentences (the separator "." Is a period), there are several phrases in the sentence (separators "," is a comma, ";" is a semicolon and "." Is a period), the phrase contains words ( separator "" - space, "," - comma, ";" - semicolon and "." - period).

With such a disassembly in PHP, a multidimensional array will turn out easily, but the algorithm will be very ugly: the number of separators grows, and the absence of a connection between adjacent paragraphs will guarantee duplication of sentences, phrases and words.

By parsing strings, you can immediately convert sequences of digits to numbers, and boolean values ​​to true and false. But this is particular, the key information will not appear anyway, because the key is the meaning, only a numeric index can be created automatically.

Complex separators

Outputting a PHP array to a string is often used for business purposes. The configuration file is traditionally written line by line, and the name is separated from the value by the equals or colon.

With such a solution, the output of the array in PHP is done to a file, the separation of lines is automatically obtained, and with reverse recognition, associative arrays are easily obtained.

By reading the file, the programmer gets the lines, and by splitting each line by "=" or ":", he gets the name and its meaning. A very popular manipulation, although it is more modern to use XML notation on the simple basis that, in addition to names and values, you can store and restore additional data, for example, variable attributes.

In the example with paragraphs (for example, natural text to build a dictionary or the result of parsing to create a data sample), it is not a specific procedure for converting a string to an array that is important, but a complex solution for all paragraphs or blocks of information.

Typically, such a task will require a reverse solution, when the generated "set" of data will need to be used to search for information in it or to assemble it back into a string.

Disassembling and reassembling strings - data validation

In PHP: arrays to string is the exact solution. If the initial information could have syntax errors, extra spaces, incorrect characters, then they will not be present during parsing. The result of transformation of the initial information according to the unwritten laws of programming is carried out strictly formally, and the result will be clearly decomposed into shelves.

The reverse procedure will create the correct source string. If we compare the amount of initial information and the result of the inverse transformation, then we can draw conclusions about where errors were made or data loss occurred. In PHP, the length of the array, in the context of the original string length, can allow one to draw the desired conclusions.

Time, date and event labels

In the development of critical projects, when creating control objects, for example, time or events, a string is one representation of data, and an array is another. But in application they are equivalent.

When you need to perform mathematical or logical calculations, the programmer manipulates the array, when you need to save the data, he uses the lowercase version.

Database field access indices are a real practice of MySQL and PHP working together, arrays per row = one index across rows of several database tables. If the database contains a dozen tables, and in each table the rows can be selected by a combination of names (values) in a certain combination, then having formed arrays of access to rows, you can subsequently have access to them using the index formation algorithm, and not by searching in the database ...

Converting an array to a string can be viewed as an algorithm for forming the desired index, while the contents of the array are formed under the control of completely different events or user actions.

Merging arrays

PHP functions allow you to manipulate arrays freely. But there are always tasks to make a selection of unique data or find data in an array.

The first problem is solved iteratively: an array (or several arrays) is iterated over and a string of unique values ​​is formed - an obvious solution, but not the most efficient one.

Finding data in an array is also a cycle, and if there are many elements, then the cycle will be quite long and take noticeable time. You can send an array to a string and use the strpos () function to find an occurrence of the required element, but this will cause the problem of detecting an erroneous occurrence.

For example, the word "tray" was searched, but its occurrence was found in the word "hammer". You can get rid of such errors if all array elements are merged into a string using a special separator, which will avoid ambiguity.

If the line contains "[tray]" and "[hammer]", then there will be no problems with the search.

But there is no guarantee that the strpos () function works faster than a loop that iterates through the elements of an array on real data volumes.

The best solution is when the array or string does the right thing on its own. If we complicate arrays a little and simplify strings, because the first is a special case of an object, and the second is traditional serialization, then everyone will do their own thing.

At the right time, an object is an array, and when a string is needed, it will be a string. In this case, it is absolutely not necessary to have both an array and a string in the object at the same time. It is possible to build a unique data structure with fast access. And move the "array" and "string" logic into the object's methods.

The object-oriented approach simplifies the solution of many tasks of processing line information, allows you not to focus on arrays, loops and the function of processing lines of PHP itself.

Both strings and arrays are the real meaning of reality, scope, task. There is no such task - to send arrays to a string to PHP. But there is a task to get a paragraph (sentence, phrase, word, number ...) based on the results obtained in the previous algorithm.

The previous algorithm carries a meaning, and the exact expression of this meaning is contained in an array. The next stage of the algorithm is the transformation of the meaning into another representation, convenient for further processing or application.

Considering the algorithm as the dynamics of meaning and data transformations, it is possible to form reliable, understandable and effective transformations.