Concatenating an array into a string php. Efficient programming in PHP: arrays to strings. Information: characters, strings and data




Hello, yesterday we 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 one is called implode function. The principle of operation of this function is similar to the previous one, but we will look at it using an example:

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

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

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

implode

(PHP 3, PHP 4, PHP 5)

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

Description

string implode(string glue, array pieces)

Returns the string obtained by concatenating the string representations of the elements of the pieces array, inserting a glue string between adjacent elements.

Example 1: Usage example implode()

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

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

Comment: This function is safe to process data in binary form.

This function combines the values ​​of array elements into a string. To combine the keys of array elements, use the following code:

php implode for nested arrays

If you pass a multidimensional array to implode, you will receive 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

Converting data from one representation to another is a popular, often the only, mechanism for solving a 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 structures make it possible to create optimal solutions for processing information as it is presented.

Information: characters, strings and data

In its “pure” form, information is a string of characters, speech or a sequence of signals. Strings, arrays and objects appear in programming - these are variants of artificial string 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 delimiter character "x" and splits the string "string" using it. The resulting array contains exactly the number of elements (lines) that are contained between the "x" characters. The separator symbol may not necessarily be the classic one:

  • comma;
  • dot;
  • 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 counted, in the second case, the number of elements. Since the delimiter character is not included in the array elements, the value of count() will be equal to the number of delimiters in the converted string minus one.

In PHP reverse transformation, arrays to string are converted with a delimiter character (can be empty), and all data (numbers and Boolean expressions) are merged into one string. An element of an array can be another array, but the programmer must handle this case specifically. 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 associative elements are converted, key information is lost. In particular, the elements "plum" and "peach" will be stripped of their keys.

Data delimiters and keys

Do not consider periods, commas, colons, etc. as delimiters. 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 indexes will have nowhere to come from.

Parsing a string by delimiter always produces strings. But this is not a reason to stop there. Having parsed one line into its component elements, you can move on.

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

With this disassembly in PHP, a multidimensional array can be easily obtained, but the algorithm will be very ugly: the number of separators increases, and the lack of connection between adjacent paragraphs is guaranteed to ensure duplication of sentences, phrases and words.

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

Complex separators

Printing a PHP array to a string is often used for utility purposes. A configuration file is traditionally written line by line, with an equals symbol or a colon separating the name from the value.

With this solution, the output of an array in PHP is done in a file, string division is automatically obtained, and with reverse recognition, associative arrays are easily obtained.

By reading the file, the programmer gets the lines, and by breaking each line by "=" or ":", he gets the name and its value. A very popular manipulation, although it is more modern to use XML notation for the simple reason that in addition to names and values, additional data can be stored and restored, 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), what is important is not the specific procedure for converting a string into an array, but a comprehensive 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 source information could have syntax errors, extra spaces, or incorrect symbols, then they will not be there during parsing. The result of transforming the initial information according to the unwritten laws of programming is carried out strictly formally, and the result will be clearly laid out on the shelves.

The reverse procedure will produce the correct source string. If you compare the amount of source information and the result of the reverse transformation, you can draw conclusions about where errors were made or data loss occurred. In PHP, the length of an array in the context of the original length of the string can allow us to draw the necessary conclusions.

Time, date and event tags

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

When it is necessary to perform mathematical or logical calculations, the programmer manipulates the array; when it is necessary to store data, he uses the string version.

Access indexes to database fields - a real practice of the joint action of MySQL and PHP, arrays in a row = one index on the 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 created row access arrays, you can subsequently have access to them using an index formation algorithm, and not by searching in the database .

Converting an array into a string can be considered 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 freely manipulate arrays. But problems always arise to select unique data or find data in an array.

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

Finding data in an array is also a cycle, and if there are a lot of elements, then the cycle will be quite long and will take a noticeable amount of time. It is possible to send an array to a string and use the strpos() function to find an occurrence of the desired element, but this will introduce the problem of detecting an erroneous occurrence.

For example, the word “tray” was searched for, and its occurrence was found in the word “hammer”. You can get rid of such errors if you merge all the elements of the array 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, on real amounts of data, the strpos() function will work faster than a loop iterating over array elements.

The best solution is for the array or string to do the right thing on its own. If we somewhat complicate arrays and simplify strings, because the former are a special case of an object, and the latter are traditional serialization, then everyone will do their own thing.

At the right time, the 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. You can build a unique data structure with fast access. And put the “array” and “string” logic into object methods.

The object-oriented approach simplifies the solution of many problems of processing string information; it allows you not to focus on arrays, loops, and the string processing function of PHP itself.

Both strings and arrays are the real meaning of reality, application, task. There is no such task - sending arrays to strings in PHP. But there is a task to obtain 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 the array. The next stage of the algorithm is the transformation of meaning into another representation, convenient for further processing or application.

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

If you need to convert a PHP array into a string, there are several tools for this. The use of a particular tool depends on your goals.

1. 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 produce the line: 1|2|3

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

2. 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 save an array into a string and then convert it back to an array. You can save the array to a file or database, and then restore it the next time you run the script.
Read more: serialize

$array = array("1" =>; "elem 1", "2"=> "elem 2", "3" => "elem 3"); $string = serialize($array); echo $string; // will produce the line: 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. json_encode() function

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 for data transfer. You will have to use this format to exchange data with javascript on the front end. More details: json_encode

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

The callback 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 true is passed as the second parameter. Details here.

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 program execution.

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

Arrays in PHP

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

PHP provides the ability to swap indices and values, which makes sense since a key is not officially stricter than a value, but you should use it carefully. For a long time, programming traditions have been appealing to the letters of the Latin alphabet. Cyrillic, as a general rule, brings with it the problem of encodings. You should not abuse the language's capabilities when you need practical and safe code.

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

The most interesting and practical feature of the PHP "arrays to string" solution is the possibility of equivalent mutual conversion.

PHP: Arrays and Strings

The PHP "arrays to string" function: $cLine = implode("/ ", $aStyle) produces a character string of 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 function $aStyle = explode("/", $cLine) creates an array of all lines that are separated by the "/" character.

When using the explode() function, it is advisable, but not necessary, to check for the presence of the desired delimiter character in the source string.

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

PHP: Print array to string via objects

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

Each will be written (read) differently, but exactly how the PHP “arrays to string” solution is executed will not matter. At their core, objects carry a certain meaning, have different structures and different methods. An example with two functions - particular. When constructing such a mechanism in PHP, arrays will be placed in a string differently in each specific case.

This opens up a lot of possibilities. One object has two arrays, another has twenty, and the common ancestor (usually the very first one is abstract) has nothing at all. By using their common ancestor methods, you don't have to worry about something not being written, read, processed, or displayed.

Thanks to inheritance, no matter what shape is used anywhere in the program, it can be represented as a string and passed back into the object of that particular shape.