PHP: an array in an array. Search in PHP array

Programming is syntax and semantics. The first is determined by the rules of the language, the second - by the experience of the developer. Regarding arrays, the developer can objectively load the syntax with semantics. This is not an object, but not an array in the traditional sense. PHP makes it possible to create arrays of variables of various types, including themselves. An element of an array can be a function, that is, the ability to load an array with a real algorithm, real meaning.

The syntax is stable, but varies from version to version and may not always be compatible, even from the bottom up. Software portability is a well-forgotten achievement of the last century. Semantics develops and can always be applied not only in any version of any language; it has become a tradition to use syntactic constructions to express what language rules did not even provide for. Using arrays as an example, this can be most easily understood.

Array Design

An array in PHP has convenient syntax and functionality. This type of data can be described in advance, but it is often convenient to create arrays on the fly as needed.

public $ aNone = array (); // the array is described and contains nothing

public $ aFact = array ('avocado', 'peach', 'cherry'); // there are three elements in this array

Creating an array in the process of checking a condition:

$ cSrcLine = 'line of the analyzed data';

for ($ i = 0; $ i <13; $ i ++) {

$ cUserLine = inputUserLine (); // input something

if (checkFunc ($ cSrcLine, $ cUserLine) {

$ aResult [] = 'Yes'; // add to the PHP array

} else {

$ aResult [] = 'No';

}

}

As a result of the execution of this example, an array of 13 elements will be created, the values ​​of which will be only the lines 'Yes' or 'No'. Elements will receive indices from 0 to 12. The same effect can be obtained by first writing the "future" PHP array to a string:

$ cFutureArray = '';

for ($ i = 0; $ i <13; $ i ++) {

$ cUserLine = inputUserLine (); // input something

if ($ i> 0) {$ cFutureArray. = '|'; }

if (checkFunc ($ cSrcLine, $ cUserLine) {$ cFutureArray. = 'Yes';

} else {$ cFutureArray. = 'No'; }

}

$ aResult = explode ('|', $ cFutureArray);

php array to string

Multidimensional Arrays

Many site management systems (SMS) use arrays "on a grand scale." On the one hand, this is good practice, on the other hand, it makes application difficult. Even if the author understands the doctrine of "PHP array in array", then you should not abuse it: not only the developer will have to get used to complex notation. Often, after a while, the creator himself will remember for a long time what he wrote at first:

return array (

'view_manager' => array (41, 'template_path_stack' => array (__DIR__. '/../view',),

'router' => array ('routes' => array ('sayhello' => array (

'type' => 'Zend \ Mvc \ Router \ Http \ Literal',

'options' => array ('route' => '/ sayhello', 'defaults' => array (

'controller' => 'Helloworld \ Controller \ Index', 'action' => 'index',))))),

'controllers' => array ('invokables' => array (

'Helloworld \ Controller \ Index' => 'Helloworld \ Controller \ IndexController'))

);

This is a sample practice of “PHP-array in array” from ZF 2. It is not very inspiring at first, but it works and, possibly, makes this framework successful (example from the ZendSkeletonApplication / module / Helloworld / config / module.config.php module).

remove php array element

An array is an important data construction during design and development. Its multidimensional version was once popular, but over time there remained a need for arrays with a maximum of two to three dimensions. It’s simpler and more understandable, but from the point of view of professionalism, when something starts to multiply, it means that something in the statement of the problem or in the code is not so.

Simple, accessible and understandable

When creating an array in php on php, it is best to be limited to two or three levels. Despite its stability and reliability, PHP makes mistakes when processing syntactic constructs. You can put up with this, having a good code editor, getting used to accurately count brackets and commas. However, PHP does not control data types (this is the karma of modern programming) and allows the developer to practice semantic errors.

The rule to control the types of variables or your own ideas of turning semantics into syntax is often an inadmissible luxury. This is a loss of script speed, code readability, ... because simplicity in coding is always essential.

PHP has a significant negative feature: when an ambiguity occurs, the script simply freezes. Not all debuggers cope with unforeseen circumstances, and a lot depends on the experience and intuition of the developer. The simpler the algorithm, the more accessible the information is structured, the more likely it is to find a mistake or not to make it at all.

Characteristically, when the first arrays appeared, data options in the form of structures were proposed - a clumsy attempt to create something from various data types. The former survived and acquired a new efficient syntax; the latter went down in history.

Simple and associative arrays

Writing a two-dimensional array is another pair of brackets "[" and "]", for example: $ aSrcData [1] [2] means accessing the element [2] of the array [1] included in the $ aSrcData array. There is no requirement in PHP to declare data in advance. Any declared information can always be checked for existence.

It is very effective to create something only when it is needed, in the form in which it was required, and destroy it when the need has disappeared. Using meaningful names as keys (indices), one can obtain readable constructions meaningful in the context of the current place in the algorithm:

$ aAnketa ['name'] = 'Ivanov';
$ aAnketa ['age'] = 42;
$ aAnketa ['work'] = 'Director';
$ aAnketa ['active'] = true;
$ aTable [] = $ aAnketa;

$ aAnketa ['name'] = 'Petrov';
$ aAnketa ['age'] = 34;
$ aAnketa ['work'] = 'Manager';
$ aAnketa ['active'] = true;
$ aTable [] = $ aAnketa;

$ aAnketa ['name'] = 'Afanasyev';
$ aAnketa ['age'] = 28;
$ aAnketa ['work'] = 'Worker';
$ aAnketa ['active'] = false;
$ aTable [] = $ aAnketa;

$ sOne. = implode (";", $ aTable [1]). '<br/>'; // second PHP array to string
$ sOne. = $ aTable [1] ['work']; // access to one element of the second array

The result of this example (the first array is ordinary, the keys in it begin with 0, the second array is associative, it has four keys: 'name', 'age', 'work', 'active'):

$ sOne = 'Petrov; 34; Manager; 1 <br/> Manager ';

In this simple example, you can see how the created questionnaire can be applied to all employees. You can create an array of employees with indices by personnel numbers and, if you need a specific employee, then select it by personnel number.

If an organization has departments, or there are seasonal workers, or it is necessary to separately identify working pensioners ... the "PHP array in array" design is very convenient, but you should never get carried away by dimension. Two to three dimensions is the limit for an effective solution.

search in php array

Array keys

If earlier it mattered how everything was arranged, then in recent years the traditions of the binary era, when the programmer wanted to know how the array elements are stored and wanted to have direct access to them, have been completely forgotten. There are many character encodings that occupy more than one byte in memory. The word "bit" can now be found only in bit search operations, but searching in a PHP array is a separate topic. Access to elements can be simple and associative. In the first case, the elements of the array (having any of the types available in PHP) are numbered 0, 1, 2, ... In the second case, the programmer indicates his own index, often referred to as the "key" to access the desired value.

$ aLine ["fruit"] = "orange"; // here PHP array key = "fruit"

or (so that everything is correct in compliance with the encoding of the page and code):

$ aLine [iconv ('UTF-8', 'CP1251', 'fruit')] = iconv ('UTF-8', 'CP1251', 'orange');

When adding a new value to the $ aLine array:

$ aLine [] = iconv ('UTF-8', 'CP1251', 'peach');
$ aLine [iconv ('UTF-8', 'CP1251', 'vegetable')] = iconv ('UTF-8', 'CP1251', "cucumber");
$ aLine [] = iconv ('UTF-8', 'CP1251', 'Eggplant');

as a result of the loop:

foreach ($ aLine as $ ck => $ cv) {
$ cOne. = $ ck. '='. $ cv. '<br/>';
}

will be received:

fruit = orange
0 = peach
vegetable = cucumber
1 = eggplant

PHP array key when adding the elements 'peach' and 'eggplant' is formed sequentially from 0, and when specifying its value will be equal to this value.

Removing elements from an array

php remove array

The easiest way is to remove the element of the PHP array during its processing. In this case, for example, as a result of the execution of the loop, the original array is scanned, and a new one is formed into which unnecessary elements are simply not written.

You can do it easier. If we apply to the last example:

unset ($ aLine [0]); // delete the element of the PHP array

then the result will be:

fruit = orange
vegetable = cucumber
1 = eggplant

There are many options for manipulating array elements. For example, using the functions: implode () and explode (), you can write a PHP array into a string with one separator, and parse it back into another array using a different separator.

To simply delete the entire array in PHP, just write: unset ($ aLine);

It's enough.

Array search

PHP contains special search functions array_keys (), array_values ​​(), array_key_exists (), and in_array (), however before deciding to use them, you should consider the possibility of performing a search in the PHP array on your own.

php array key

Any project has a specific subject area, constructed arrays, especially when part of the semantics is transferred to the syntax and represented by a set of very specific meaningful keys. This allows you to perform your own search functions, which can also be identified meaningfully.

In PHP, you can call functions whose name is determined during program execution. A very practical example from the PHPWord library, which allows you to read and create MS Word documents:

$ elements = array ('Text', 'Inline', 'TextRun', 'Link', 'PreserveText', 'TextBreak',
'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'Footnote',
'Endnote', 'CheckBox', 'TextBox', 'Field', 'Line');

$ functions = array ();

for ($ i = 0; $ i <count ($ elements); $ i ++) {
$ functions [$ i] = 'add'. $ elements [$ i];
}

As a result, the $ functions array will receive the values ​​of the $ elements array, that is, the names of the real functions that perform work with the real elements of the document.

By calling the $ functions [4] function for $ elements [4], you can get the perfect search and fast results.

Sort Items

The task of sorting data is important, and PHP offers several functions for this: sort (), rsort (), asort (), ksort (), ... As the elements ascend and descend, the second two functions preserve the relationship between keys and values. Sometimes it makes sense to mix the values ​​of the array randomly - shuffle ().

php value in array

Using PHP functions for sorting, one should not forget that elements can have not only different types, but also not quite natural content. First of all, you need to be very careful about sorting strings containing Russian letters, sorting dates, as well as numbers that are written in different formats.

php array in array

The best way to write your own perfect solution, at least at the stage of testing the script, is manual sorting. She will help to foresee unforeseen situations.

String Arrays

Thanks to the functions implode () and explode (), the array can be easily transformed into a string and retrieved. This allows you to store data in a compact representation and deploy it in a convenient state as needed.

An array turned into a string opens up new possibilities. For example, the task of searching for keywords in the text requires that the search is not re-added.

$ cSrcLine = 'Text Text ListItemRun TextBox ListItem TextBox Check Box CheckBox TextBox Footnote';

$ aSrc = explode ('', $ cSrcLine);
$ cDstLine = '';

for ($ i = 0; $ i <count ($ aSrc); $ i ++) {
$ cFind = '['. $ aSrc [$ i]. ']';
if (! is_integer (strpos ($ cDstLine, $ cFind))) {
$ cDstLine. = $ cFind;
}
}
$ aDst = explode ('] [', $ cDstLine);

$ cOne = implode (';', $ aDst);

As a result, the variable $ cOne will receive only those values ​​from the original string that are found there once once: "Text; ListItemRun; TextBox; ListItem; Check; Box; CheckBox; Footnote".

Russian language in keys and meanings

It is not recommended to use anything related to national encodings in syntactic constructions. The Russian language, like all other languages ​​whose characters go beyond az, will not create problems, being in the data area, but not in the syntax of the code. Sometimes even a simple PHP task “display the array on a printer or on the screen” will lead to “cracks”, and more often it just stops the script.

PHP is a loyal language and tolerant of national encodings, but there are a lot of situations where the amount of work done has to be done repeatedly only because a key value pops up at the right place and at the right time, which it will not be possible to recognize.

PHP syntax and language environment

It should be remembered that the syntax of PHP is one thing, but the constructions of this syntax “deal” with other applications, with the operating system, with hardware options. There are many options; it is never possible to foresee everything.

The rule “there is only code in the code, but there is all kinds of information at the input, inside, and at the exit” will help to avoid unforeseen surprises. The PHP value in the array can be “Russian”, but the key to it must be syntactically correct not only from the standpoint of the given language, but also from the standpoint of its working environment.

Source: https://habr.com/ru/post/K17453/


All Articles