/ / Php: array in array. PHP array search

PHP: an array in an array. PHP array search

Programming is syntax and semantics.The first is determined by the rules of the language, the second - by the developer experience. In regards to arrays, the developer can substantively load the syntax with semantics. This is not an object, but not an array in the traditional sense. PHP allows you 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, a real meaning.

Синтаксис стабилен, но меняется от версии к versions and may not always be compatible even from the bottom up. Program 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 constructs to express that the rules of the language have not even been provided. Using the example of arrays, this can be understood most simply.

Array construction

An array in PHP has a convenient syntax and functionality. This data type 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"); // three elements in this array

Creating an array in the process of checking a condition:

$ cSrcLine = "line of data being analyzed";

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

$ cUserLine = inputUserLine (); // enter something

if (checkFunc ($ cSrcLine, $ cUserLine) {

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

} else {

$ aResult [] = "No";

}

}

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

$ cFutureArray = "";

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

$ cUserLine = inputUserLine (); // enter 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 "in a big way". On the one hand, this is a good practice, on the other hand, it makes application difficult. Even if the author understands the doctrine of "PHP array in an 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 long remember what he wrote at first:

return array (

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

"router" => array ("routes" => array ("sayhello" => array (

"type" => "ZendMvcRouterHttpLiteral",

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

"controller" => "HelloworldControllerIndex", "action" => "index",))))),

"controllers" => array ("invokables" => array (

"HelloworldControllerIndex" => "HelloworldControllerIndexController"))

);

This is a sample practice of "PHP array in an array" from ZF2. Not too inspiring at first, but it works and, perhaps, makes this framework successful (example from the ZendSkeletonApplication / module / Helloworld / config / module.config.php module).

remove php array element

An array is an important construction of data duringdesign and development. Its multidimensional variant was once popular, but over time there was a need for arrays with a maximum of two or three dimensions. It is easier and more understandable, but from the point of view of professionalism, when something starts to multiply, it means that something in the formulation of the problem or in the code is different.

Simple, accessible and understandable

Создавая на php массив в массиве, лучше всего limited to two or three levels. Despite the stability and reliability of PHP makes errors in the processing of syntaxes. With this you can put up with 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.

Rule to control variable types orown ideas of transforming semantics into syntax are often an impermissible luxury. This is a loss of script speed, readability of the code, ... because simplicity in coding is always essential.

У PHP есть существенная отрицательная черта:when uncertainty occurs, the script just hangs. Not all debuggers deal with unforeseen circumstances, and much depends on the experience and intuition of the developer. The simpler the algorithm, the more easily the information is structured, the more likely it is to find a mistake or not to allow it at all.

It is characteristic that when the first arrays appeared,Variants of data were proposed in the form of structures - a clumsy attempt to create something from various types of data. The first survived and acquired a new efficient syntax, the second went down in history.

Simple and associative arrays

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

It’s very effective to create something onlywhen it is needed, in the form in which it was needed, and destroy it when the need for it has disappeared. Using meaningful names as keys (indexes), you can get readable constructions 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"] = "Afanasyev";
$ aAnketa ["age"] = 28;
$ aAnketa ["work"] = "Work";
$ aAnketa ["active"] = false;
$ aTable [] = $ aAnketa;

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

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

$ sOne = "Petrov; 34; Manager; 1
Manager";

In this simple example, you can seeThe 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 him by personnel number.

If the organization has divisions, or there areseasonal workers, or it is necessary to separately allocate working pensioners, ... the construction of a "PHP array in an array" is very convenient, but you should never get involved in the dimension. Two or three measurements - the limit for an effective solution.

search in php array

Array Keys

Если раньше имело значение, как все устроено, то In recent years, the traditions of the binary era, when the programmer wanted to know exactly how the array elements are stored, and wanted to have direct access to them, were completely forgotten. There are many character encodings that take more than one byte in memory. The word "bit" can be found now except in bit search operations, but a 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 his own index, often referred to as the “key” for accessing the desired value.

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

or (so that everything is correct in compliance with the page encoding 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 cycle:

foreach ($ aLine as $ ck => $ cv) {
$ cOne. = $ ck. "=". $ cv. "
";
}

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 if you specify its value will be equal to this value.

Removing elements from an array

php remove array

The easiest way is to remove a PHP array item duringprocessing it. In this case, for example, as a result of the execution of the loop, the original array is viewed, and a new one is formed, into which unnecessary elements are simply not written.

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

unset ($ aLine [0]); // remove PHP array element

then the result will be:

fruit = orange
vegetable = cucumber
1 = eggplant

Вариантов манипулирования элементами массивов can design many. For example, using the functions: implode () and explode (), you can write a PHP array into a string with one delimiter, and disassemble it back into another array with another delimiter.

To simply remove 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 (), but before deciding to use them, you should consider the ability to perform a search in a PHP array on your own.

php array key

Any project is a specific subject area,constructed arrays, especially when part of the semantics is transferred to the syntax and is represented by a set of quite specific 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 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 $ functions [$ i] = "add". $ elements [$ i];
}

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

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

Sort items

The task of sorting data is important, andPHP 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 an array at random - shuffle ().

php value in array

Using PHP functions for sorting should notforget that elements can have not only a different type, but also not quite natural content. First of all, you need to be very careful about sorting lines 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 during the script testing phase, is manual sorting. It will help provide for unforeseen situations.

Lower case arrays

Thanks to the implode () and explode () functionscan be easily transformed to a string and get back. This allows you to store data in a compact view and deploy it to a convenient state as needed.

The array turned into a string opens up new possibilities. For example, the task of finding keywords in the text requires that the found is not added again.

$ 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 receive only those values ​​from the source line that are found there once: "Text; ListItemRun; TextBox; ListItem; Check; Box; CheckBox; Footnote".

Russian language in keys and values

It is not recommended to use anything that is connected.with national encodings, in syntactic constructions. Russian, like all other languages, the characters of which are beyond the bounds of a-z, will not create problems when in the data area, but not in the syntax of the code. Sometimes even a simple PHP task to "output an array to a printer or to a screen" will lead to "cracks", and more often it will simply stop the script.

PHP is a loyal language and tolerant ofnational codings, but there are a lot of situations where the amount of work done has to be done again only because the key value will appear in the right place at the right time, which cannot be recognized.

PHP syntax and language environment

Remember that PHP syntax is one thing, butconstructs 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 "in the code there is only code, and at the input,there is any information inside and at the exit ”will help to avoid unexpected 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 environment.