ComputersProgramming

PHP: array in an array. Searching in an array of PHP

Programming is syntax and semantics. The first is determined by the rules of the language, the second by the developer's experience. With respect to arrays, the developer can objectively load the syntax with semantics. This is not an object, but no longer 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, with real meaning.

The syntax is stable, but varies from version to version and can not always be compatible, even from the bottom up. Portability programs - well forgotten achievement of the last century. Semantics develops and can always be applied not only in any version of any language; It became a tradition to use syntactic constructions to express the fact that there were not even rules for the language. On the example of arrays, this can be understood most simply.

Array construction

The 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'); // in this array there are three elements

Creating an array while checking a condition:

$ CSrcLine = 'string of parsed 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 whose values will only be the lines 'Yes' or 'No'. Elements will get indices from 0 to 12. The same effect can be obtained by writing a "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);

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 "PHP-array in an array," then it should not be misused: not only will the developer 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 the "PHP array in array" from ZF 2. It does not inspire much at first, but it works and perhaps makes this framework successful (example from the ZendSkeletonApplication / module / Helloworld / config / module.config.php module).

An array is an important data structure during design and development. Its multi-dimensional version was once popular, but over time, there was a need for arrays of a maximum of two or three dimensions. So it's easier 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 the case.

Simple, accessible and understandable

Creating a php array in an array, it is best to limit to two or three levels. Despite the stability and reliability of PHP, it allows errors in the processing of syntactic constructions. This can be tolerated by having a good code editor, getting used to exactly counting 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 of controlling the types of variables or one's own ideas of turning semantics into syntax is often an inadmissible luxury. This is a loss of script speed, readability of the code, ... therefore simplicity in coding always has a significant value.

PHP has a significant negative feature: when the uncertainty arises, the script simply hangs. Not all debuggers cope with unforeseen circumstances, and much depends on the experience and intuition of the developer. The simpler the algorithm, the more structured the information is, the more likely it is to find an error or not to admit it at all.

It is characteristic that when the first arrays appeared, data variants were proposed in the form of structures - an awkward attempt to create something from different types of data. The first survived and acquired a new effective 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] refers to the element [2] of array [1] entering the $ aSrcData array. In PHP, there is no requirement to declare the 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 to destroy it when the need for it has disappeared. Using meaningful names as keys (indices), you can get readable constructs that are 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'] = 'Afanasiev';
$ AAnketa ['age'] = 28;
$ AAnketa ['work'] = 'Worker';
$ AAnketa ['active'] = false;
$ ATable [] = $ aAnketa;

$ SOne. = Implode (";", $ aTable [1]). '
'; // the second PHP array in a string
$ SOne. = $ ATable [1] ['work']; // reference to one element of the second array

The result of this example (the first array is normal, the keys in it start with 0, the second array is associative, there are four keys in it: 'name', 'age', 'work', 'active'):

$ SOne = 'Petrov; 34; Manager; 1
the 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 indexes by service numbers and, if you need a particular employee, then select it by the employee number.

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

Keys for working with arrays

If before it mattered how everything works, then in recent years the traditions of the binary era, when the programmer wanted to know exactly how the elements of the array were stored, and wanted to have direct access to them, were completely forgotten. There are many character encodings that take up more than one byte in memory. The word "bit" can now be found only in bit search operations, but the search 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 specifies its own index, often called the "key" to access the desired value.

$ ALine ["fruit"] = "orange"; // here the PHP key of the array = "fruit"

Or (so that everything is correct with the encoding of the page and the code):

$ ALine [iconv ('UTF-8', 'CP1251', "Fruit")] = iconv ('UTF-8', 'CP1251', "orange");

When adding $ aLine to a new value:

$ 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 cycle:

Foreach ($ aLine as $ ck => $ cv) {
$ COne. = $ Ck. '='. $ Cv. '
';
}

Will receive:

Fruit = orange
0 = peach
Vegetable = cucumber
1 = eggplant

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

Removing items from an array

The easiest way to remove an element of a 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 created, into which unnecessary elements are simply not written.

It is possible to act easier. If the last example is applied:

Unset ($ aLine [0]); // remove the element of the PHP array

The result will be:

Fruit = orange
Vegetable = cucumber
1 = eggplant

Variants of manipulating elements of arrays can be constructed a lot. For example, using the functions: implode () and explode (), you can write a PHP array into a single-delimited string, and parse it back into another array - another separator.

To simply delete a whole array in PHP, simply write: unset ($ aLine);

It's enough.

Search in an array

PHP contains special search functions array_keys (), array_values (), array_key_exists (), and in_array (), but before you decide to use them, you should consider doing a search in the PHP array on your own.

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

In PHP, you can call functions whose name is defined during the execution of the program. 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 $ Functions [$ i] = 'add'. $ Elements [$ i];
}

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

Calling $ functions [4] for $ elements [4], you can get an ideal search and a quick result.

Sorting items

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

Using the 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 the lines containing Russian letters, sorting the date, as well as numbers that are recorded in different formats.

The best way to write an ideal solution yourself, at least in the script testing phase, is manual sorting. It will help to anticipate unforeseen situations.

Lowercase Arrays

With the implode () and explode () functions, the array can be easily transformed into a string and returned. This allows you to store data in a compact view and deploy them in a convenient state as needed.

An array in a row opens up new possibilities. For example, the task of searching for keywords in the text requires that the search result not be added repeatedly.

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

$ ASrc = explode ('', $ cSrcLine);
$ CDstLine = '';

For ($ i = 0; $ i $ CFind = '['. $ ASrc [$ i]. ']';
If (! Is_integer (strpos ($ cDstLine, $ cFind))) {
$ CDstLine. = $ CFind;
}
}
$ ADst = explode ('] [', $ cDstLine);

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

As a result, the $ cOne variable will only receive those values from the source string that occur there one at a time: "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 cause problems in the data area, but not in the syntax of the code. Sometimes even a simple task in PHP "to output an array to a printer or to a screen" will lead to "krakozyabram", and more often just stop the script.

PHP is a loyal language and tolerant of national encodings, but there are a lot of situations when the amount of work that has to be done has to be done again only because a key value pops up at the right place and at the right time, which can not be recognized.

PHP Syntax and Language Environment

Remember that PHP syntax is one thing, but the syntax of this syntax "deals" with other applications, with an operating system, with hardware options. There are many options, it is never possible to envisage everything.

The rule "in the code there is only code, and at the input, inside, and on the output there is any information" will help to avoid unforeseen surprises. PHP-value in the array can be "Russian", but the key to it must be syntactically correct not only from the positions of the given language, but also from the positions of its working environment.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.atomiyme.com. Theme powered by WordPress.