PHP: arrays in a string. Convert strings to arrays and vice versa

Converting data from one view 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 constructs make it possible to create optimal solutions for processing information in the form in which it is presented.

Information: characters, lines 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 lowercase constructions. Numbers are strings, too, but numbers, not characters.

php array output

Converting a string to an PHP array allows you 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 breaks the string 'string' along it. Exactly the same number of elements (strings) that are contained between the characters 'x' gets into the resulting array. The separator may not necessarily be the classic:

  • comma;
  • point;
  • semicolon.

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

The length of the string is strlen () in PHP, the length of the array 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 elements of the array, the value of count () will be equal to the number of separators in the converted string minus one.

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

Recursion and implode () function

In this example, there is no problem converting PHP arrays to strings until there is another array among their elements. When transforming associative elements, key information is lost. In particular, the “drain” and “peach” elements will be deprived of their keys.

Data Separators and Keys

Dots, commas, colons, etc. should not be considered as separators. This is a special case of data separation from each other. When converting a string to PHP, a multidimensional array will fail, and associative indices will come from nowhere.

When parsing strings by separator, strings are always obtained. But this is not a reason to stop there. Having disassembled one line into the constituent elements, we can go further.

php multidimensional array

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

With such a disassembly in PHP, a multidimensional array will turn out to be easy, but the algorithm will be very ugly: the number of separators is growing, and the lack of communication between adjacent paragraphs is guaranteed to ensure duplication of sentences, phrases and words.

Parsing strings, you can immediately convert sequences of numbers to numbers, and logical values ​​to true and false. But this is particular, key information will not appear anyway, because the key is the point, you can automatically create only a numerical index.

Integrated Separators

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

With this solution, the array is outputted to PHP in a file, line separation is automatically obtained, and with reverse recognition, associative arrays are easily obtained.

Reading a file, the programmer gets the lines, and breaking each line by "=" or ":", gets the name and its value. 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, attributes of variables.

convert string to php array

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

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

Dismantling and assembling strings - data validation

In PHP: arrays in a string is the exact solution. If the source information could have syntax errors, extra spaces, incorrect characters, then there will be no disassembly. The result of the transformation of the source 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 allow you to create the correct source string. If we compare the amount of initial information and the result of the inverse transformation, 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 may allow us to draw the necessary conclusions.

Time, Date, and Event Labels

In the development of critical projects, when creating management objects, for example, time or events, a row is one representation of the 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 data, he uses the line option.

php array length

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

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

Merge Arrays

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

The first task is solved iteratively: an array (or several arrays) is selected 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 take noticeable time. You can send an array to a string and use the strpos () function to find the occurrence of the required element, but this will cause the problem of detecting an erroneous occurrence.

For example, the word "tray" was searched, and its occurrence in the word "hammer" was found. You can get rid of such errors if all the elements of the array are merged into a string using a special separator, which will allow to 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 on real amounts of data faster than a loop that iterates over the elements of an array.

Object Solution: Arrays + Strings

The best solution is when an array or string itself performs the correct action. If you complicate arrays a little and simplify the lines, because the former is a special case of the object, and the latter is traditional serialization, then everyone will do his own thing.

Object Solution: Arrays + Strings

At the right time, an object is an array, and when you need a string, it will be a string. At the same time, it is not necessary to have both an array and a string at the same time in the object. You can build a unique data structure with quick access. And the logic "array" and "string" put in the methods of the object.

The object-oriented approach simplifies the solution of many problems of processing line information, eliminates the need to focus on arrays, loops and the function of processing strings of PHP itself.

The dynamics of meaning

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

The dynamics of meaning

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


All Articles