Arrays are very widely used in PHP scripts.


An array is a collection of elements, each of which can be accessed by index or name. All arrays in PHP are associative, i.e. consist of "key"="value" pairs.

The $arr array contains one pair of values. The key in it will be the value "car", and the value - "Seagull".

The value of the keys can be of text or numeric type, and keys of different types can be used in one array. For example, the following code works quite well:

Sometimes there is no need to specify element keys. In this case, you can take advantage of the fact that PHP can create keys automatically when adding elements to an array. The keys will always be numeric and start from zero. For example:

"first", 1=>"second", 2=>"third"); ?>

The "=>" combination is used to separate the key from the value in an element when declaring an array.

Appeal to individual element an array is produced by its index or key:

And using the foreach construct you can quickly iterate through all the elements of an array:

$value) echo "Array element number $key is equal to "$value""; ?>

To work with archives, PHP provides a number of functions that allow you to set standard operations, such as sorting, searching or rotating an array. Let's look at the most used functions.

array_chunk() Used to divide an array into parts given size. The function returns an array of fragments of the original array.
array_combine() The function combines two arrays so that the elements of the first become the keys, and the elements of the second become the values ​​of the resulting associative array."a", 1=>"b", 2=>"c" ?>
array_count_values() Counts the number of unique values ​​in an array and how often they occur3, "b" => 1, "c" => 2 ?>
array_diff() The function highlights the difference between two arrays, i.e. elements that are in the first array and not in the second.
array_fill() Fills an array with a given value"xxx" 3=>"xxx" 4=>"xxx" ?>
array_flip() Swaps the keys and values ​​of an associative array"a", 1=>"b", 2=>"c"); $res = array_flip($arr); // $res contains "a"=>0, "b"=>1, "c"=>2 ?>
array_intersect() The function calculates the intersection of two arrays, i.e. returns all elements that are simultaneously in both arrays.
array_key_exists() The function checks whether there is a key with the same name in the array."a", 1=>"b", 2=>"c"); if(array_key_exists(1, $arr) echo "Key found"; else echo "Key not found"; ?>
array_keys() Returns an array of keys"a", 1=>"b", 2=>"c"); $res = array_keys($arr); // $res contains 0, 1, 2 ?>
array_merge() Combines one or more arrays. The values ​​of elements with the same keys are replaced by elements of the second array"a", 1=>"a", 2=>"b"); $arr2 = array(3=>"a", 0=>"b", 4=>"c"); $res = array_merge($arr1, $arr2); // $res contains 0=>"b", 1=>"a", 2=>"c", 3=>"a", 4=>"c" ?>
array_rand() Returns one random element from an array
array_reverse() Returns the original array, but in reverse order, i.e. read from end to beginning.
array_search() The function searches for an array element that matches the specified conditions. Returns the name of the corresponding key."a", 22=>"b", 33=>"c"); $key = array_search("b", $arr); // $key is 22 ?>
array_shift() Shifts all array elements to the beginning, losing the first array element.
array_slice() Retrieves a fragment of an array
array_sum() The function returns the sum of all array values
array_unique() Removes duplicate values ​​from an array
array_unshift() The inverse function of array_shift() shifts all elements to the end of the array and adds an element to the beginning.
array_values() Returns an array of values ​​from the original array"a", "y"=>"b", "z"=>"c"); $res = array_values($arr); // $res contains "a", "b", "c" ?>
array() The function creates an empty or predefined array."a", "y"=>"b", "z"=>"c"); ?>
count() Counts the number of elements in an array
in_array() Checks whether the specified value exists in the array
list() The operator allows you to assign an array to a list of variables.
sort() Array sort function

As you can see, using arrays is very simple, and most importantly, extremely convenient. Not a single large project can do without the use of arrays. We have looked at only some of the available functions, without going into the subtleties of their application for various situations. You can get more detailed information from the official manual on the website www.php.net.

extract product (12)

If I had an array like:

$array["foo"] = 400; $array["bar"] = "xyz";

And I wanted to get the first element from this array without knowing the key for it, how would I do it? Is there a function for this?

Answers

reset($array); $first = current($array);

I'm doing this to get the first and last value. This also works with more values.

$a = array("foo" => 400, "bar" => "xyz",); $first = current($a); //400 $last = end($a); //xyz

Just so we have other options: reset($arr); is good enough as long as you're not trying to store the array pointer in place, and with very large arrays it incurs a minimal amount of overhead. However, there are some problems:

$arr = array(1,2); current($arr); // 1 next($arr); // 2 current($arr); // 2 reset($arr); // 1 current($arr); // 1 !This was 2 before! We"ve changed the array"s pointer.

A way to do this without changing the pointer:

$arr; // OR reset(array_values($arr));

Benefit $arr; is that it raises a warning if the array is actually empty.

Reset($array); list($key, $value) = each($array); echo "$key = $value\n";

You can try this.
To get the first value of an array:-

"bar", "hello" => "world"); var_dump(current($large_array)); ?>

To get the first key of the array

"bar", "hello" => "world"); $large_array_keys = array_keys($large_array); var_dump(array_shift($large_array_keys)); ?>

You can do:

$values ​​= array_values($array); echo $values;

Use the reset() function to get the first element from this array without knowing the key for it as follows.

$value = array("foo" => 400, "bar" => "xyz"); echo reset($value);

output // 400

If you don't know enough about the array (you don't know if the first key is foo or bar), then the array could also be maybe empty .

So it would be better to check, especially if there is a possibility that the return value could be a boolean FALSE:

$value = empty($arr) ? $default: reset($arr);

The above code uses reset and has side effects(it resets the internal array pointer) so you may prefer to use array_slice to quickly access a copy of the first element of the array:

$value = $default; foreach(array_slice($arr, 0, 1) as $value);

Assuming what you want to get both key and value separately, you need to add a fourth parameter to array_slice:

Foreach(array_slice($arr, 0, 1, true) as $key => $value);

To get the first element as a pair(key => value):

$item = array_slice($arr, 0, 1, true);

Simple modification to obtain last element, key and value separately:

Foreach(array_slice($arr, -1, 1, true) as $key => $value);

You can add your own error handler, which can provide additional debugging information. Additionally, you can set it up to send via email.

Function ERR_HANDLER($errno ,$errstr, $errfile, $errline)( $msg=" Something bad happened.[$errno] $errstr

File:$errfile
Line:$errline

".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."

"; echo $msg; return false; ) function EXC_HANDLER($exception)( ERR_HANDLER(0,$exception->getMessage(),$exception->getFile(),$exception->getLine()); ) function shutDownFunction( ) ( $error = error_get_last(); if ($error["type"] == 1) ( ERR_HANDLER($error["type"],$error["message"],$error["file"],$ error["line"]); ) ) set_error_handler("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); register_shutdown_function("shutdownFunction"); set_exception_handler("EXC_HANDLER");

If you don't know enough about the array (you're not sure if the first key is foo or bar), then the array could also be maybe empty.

So it would be better to check, especially if there is a possibility that the return value might be a boolean FALSE:

$value = empty($arr) ? $default: reset($arr);

The above code uses reset and so has side effects(it resets the internal array pointer) so you may prefer to use array_slice to quickly access a copy of the first element of the array:

$value = $default; foreach(array_slice($arr, 0, 1) as $value);

Assuming what you want to get key and value separately, you need to add a fourth parameter to array_slice:

Foreach(array_slice($arr, 0, 1, true) as $key => $value);

To get the first element as a pair(key => value):

$item = array_slice($arr, 0, 1, true);

Simple modification to obtain last element, key and value separately:

Foreach(array_slice($arr, -1, 1, true) as $key => $value);

play

If the array is not very large, you don't really need array_slice and you can get a copy of the entire key array and then get the first element:

$key = count($arr) ? array_keys($arr) : null;

However, if you have a very large array, calling array_keys will require significant time and more memory than array_slice (both functions traverse the array, but the latter exits once array_slice has the required number of elements - that is, one).

A notable exception is when you have a first clue that points to a very large and tortuous object. In this case, array_slice will duplicate that first large object, and array_keys will only capture the keys.

PHP 7.3

PHP 7.3 implements array_key_first() and array_key_last() . They are explicitly provided to efficiently access the first and last keys without resetting the internal state of the array as a side effect.

So in PHP 7.3 the first value of $array can be accessed with

$array;

You'd still better check that the array is not empty, otherwise you'll get an error:

$firstKey = array_key_first($array); if (null === $firstKey) ( $value = "Array is empty"; // An error should be handled here } else { $value = $array[$firstKey]; }!}

PHP arrays are used everywhere. Adding and changing values ​​is usually straightforward.

Removing array elements is a special operation. You can simply delete the element, or you can delete it and use it. This nuance provides great opportunities.

PHP Arrays

PHP is a modern programming language, the functionality in terms of working with arrays is performed at a high level. The programmer has the opportunity to use regular and associative arrays, design multidimensional data structures, and have a value of any type as array elements.

There is a developed set of functions for working with arrays and special syntactic constructions. It is possible to traverse the array using your own algorithm and assign your own processing functions.

Examples of creating and using an array

The scPrint function is auxiliary. It recursively writes an array into a character string to demonstrate the results it produces.

The $aFruits array is created in the usual way: the values ​​are listed, the indexes are assigned automatically from scratch. The last comma is irrelevant and does not create another empty element.

The $aData array is created empty, then values ​​are added to it. Three are automatic, and two are with associative indexes that do not affect the overall numbering of values. Thus, the elements “plum” and “peach” have the indices “new” and “fresh”, respectively.

The $aInfo array is multidimensional and associative.

Three deletion operations show how to remove an element in a PHP array.

The first operation removes the second element from the $aFruits array, its index is 1. It should be noted that the following indices are not shifted, which means that in cyclic operations with such an array it is necessary to check the existence of the element.

The second operation deletes the last and first elements in the $aData array, which confirms that the deletion does not affect the indexes and the possibility of simultaneously deleting several elements.

The third one deletes an array within an array and an element within an array that is part of another array.

Normal removal of elements - unset

The unset function removes. No matter what. It could just be a variable or an array element. unset() is considered to be a language operator, not a function. This operator does not return any value, and it “destroys” what is passed to it as parameters. The variable or array disappears as if it never existed.

In PHP, you can remove empty array elements in different ways; in fact, what is considered an empty element depends on the programmer. However, it is not very wise to use multiple parameters in the unset() operator for this purpose. It is more practical to move group operations into group functions.

Modern computers are very fast, and PHP is very fast. But this is not a reason to create and process tons of information using cumbersome algorithms; this is an objective reason to approach the process of removing array elements in progressive ways.

Removing elements using string methods

In PHP, you can remove empty array elements in bulk by converting the array to a string and returning it back. But this case is only suitable for really empty elements, missing indexes, or for the purpose of reindexing an array.

The concept of an empty element depends on the task. Often an existing array element that contains certain information becomes empty. For example, an array records visitors. The array element contains:

  • visitor arrival time;
  • current operating mode;
  • active page;
  • last action time.

If the difference between the time of arrival and the time of the last action is more than 1 minute (or another value), we can assume that the client has left the site. Records about such clients can be deleted if the task is to monitor the list of active visitors and not use more advanced methods using JavaScript.

However, the "line" processing is good. For example, in PHP you can remove duplicate array elements like this:

Fast and affordable way. It is not necessary to use the symbols "[" and "]" to denote each element, but remember that when transforming an array into a string, you must ensure that each element is unique. The framing characters should be chosen based on the characters that are allowed in the element. An unshakable rule: each array element in a row is unique and has its place (otherwise nothing can be returned back).

This method is more convenient when the task in PHP is to remove an array element by value. You can use the array_flip function and swap the values ​​and keys, then do a classic unset. You can use the array_search function and find the key of the value you want to remove. But the lowercase version of the solution is clearer and simpler.

PHP practically does not limit the developer in anything: neither in the number of dimensions, nor in the sizes of elements. There is no point in getting involved in this. Each element should be of the minimum possible length, and the number of dimensions should tend to one.

If the number of array dimensions is more than three, this is a good reason to reconsider the decision. If an array element is longer than 4000-8000 characters, doubts should arise about the reasonableness of the constructed data picture.

This opinion does not arise from the context of the functionality of a PHP array: remove an element, add an object of a different type, change one thing to something completely different. Simplicity is the key to success not only in life, but also in the algorithm. The program should work, and not surprise with its dimensions, dimensions and scale of ideas. It's the result that matters, not the big idea.

As a modern programming language, PHP does not ignore recursion and the stack. It is fundamentally unimportant what the programmer means when he uses the array_pop() function in PHP: remove the last element of the array or simply get it into some variable.

But keep in mind that in this context, the array_pop function is a push & pop function, that is, it is a stack tool, not a delete tool.

Here it is customary to say not “delete”, but “extract”. The semantics are significantly different. However, the array_shift() function in PHP - removing the first element of an array or extracting it - has a different connotation. Here also the element is retrieved into an external variable and will not be in the array, but the indices are shifted.

When the first element is extracted from an array, all elements that follow it are shifted forward, but only the numeric indices change; the lowercase indices remain unchanged.

Delete or change: transaction history

A variable is a very long time ago, an array is a long time ago, an object is yesterday. Object-oriented programming is still only talked about, but nothing is used to its full potential. It is a rare case when superficial solutions became the subject of enthusiastic solutions and “wise” content management systems (CMS) with a lot of “body”.

Objective rule: it’s not the quantity of code that matters, but its quality! But no modern CMS has yet heeded this rule. Its authors believe that they are doing the right thing and know what they are doing.

Result (characteristic feature): none of the modern CMS is distinguished by a decent “figure” (slenderness and lightness of designs), all have an immense completeness of code, each demands respect:

  • highly qualified programmer;
  • needs installation;
  • imposes hosting requirements;
  • creates difficulties when moving to another hosting;
  • really slows down work and administration.

Programmers have been coming to the concept of rollback for a very long time; modern programming cannot imagine creating software without two functions:

  • undo;
  • redo.

It is not only human nature to make mistakes, but in any situation there must be a rollback. In modern Internet programming tools to this day, this point not only does not matter, but is also used on a very limited scale.

PHP operations on an array: removing an element, changing its type or adding something new are clear. But before there were variables, then arrays, then objects. Isn't there a reason to think about the fact that an array is just a variable over time?

An array is a data structure over time. No language to this day considers time as a factor in syntax. You don’t even have to talk about semantics: from ancient times to this day, programmers and users understand only files and folders. The maximum that development has come to, for example, in PHP, the namespace is trivially reflected in the structure of folders and files.

In this context, banal actions in PHP on an array: removing an element, changing or adding - require additional actions from the programmer. You can leave everything as it is, and it will work out as always. You can take into account every operation on data and record it in full, create and store a history of operations.

This will be a completely different level of work and a radically better quality of the result.

So, we have an array $arr and we need to get the first element of this array.

You can't just do this:

$first = $arr;

The element at index 0 may simply not be defined. For example, if the array is associative, or we did unset($arr) .

Method 1

$first = reset($arr);

Using reset we get the first element, however there is one side effect: the array pointer is also reset to the first element. Although in principle this function is intended to reset the pointer. Documentation for the reset() function.

Note that if the array is empty reset() will return false and this result will be indistinguishable from the case where the array is not empty but contains false as the first element.

$a = array(); $b = array(false, true, true); var_dump(reset($a) === reset($b)); //bool(true)

Method 2

You can use the array_shift function - it retrieves the first element and at the same time removes it from the passed array. Array_shift() documentation.

$first = array_shift($arr);

Method 3

Write your own function for these purposes:

Function array_first($array, $default = null) ( foreach ($array as $item) ( return $item; ) return $default; )

The advantage is that it does not change the original array. You can also pass a $default parameter, which will be used as the default value if the array is empty.

By the way, in the Laravel framework this function is already defined and allows you to also specify a callback to which you can pass a condition. You can for example take the first element that is greater than 10 or the first element that is not a number.

Here is the code for a more advanced function:

Function array_first($array, callable $callback = null, $default = null) if (is_null($callback)) ( if (empty($array)) ( return $default instanceof Closure ? $default() : $default; ) foreach ($array as $item) ( return $item; ) ) foreach ($array as $key => $value) ( ​​if (call_user_func($callback, $value, $key)) ( return $value; ) ) return $default instanceof Closure ? $default() : $default; )

It can be used for example like this:

$array = ; $first = array_first($array, function ($value, $key) ( return $value >= 150; )); echo $first; // 200

Method 4

The current() function is also useful for getting the first element of an array.
Usage example:

$transport = array("foot", "bike", "car", "plane"); $mode = current($transport); // $mode = "foot";

More precisely, this function is used to return the element at which the internal array pointer is located. In most cases the pointer is to the first element, however there are situations where it may not be the first element that is returned.

$transport = array("foot", "bike", "car", "plane"); next($transport); // move the pointer forward (http://php.net/manual/ru/function.next.php) $mode = current($transport); // $mode = "bike"; - i.e. the second element of the array has already returned.

Thanks to commentator Alexey Berlinskiy for this method.

If you still know ways to get the first element, write in the comments.

Was this article helpful?