php array first value

How to get the first item from an associative PHP array?

If I had an array like:

And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?

16 Answers 16

reset() gives you the first value of the array if you have an element inside the array:

It also gives you FALSE in case the array is empty.

php array first value. Смотреть фото php array first value. Смотреть картинку php array first value. Картинка про php array first value. Фото php array first value

php array first value. Смотреть фото php array first value. Смотреть картинку php array first value. Картинка про php array first value. Фото php array first value

PHP reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:

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

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

Simple modification to get the last item, key and value separately:

performance

If the array is not really big, you don’t actually need array_slice and can rather get a copy of the whole keys array, then get the first item:

A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.

PHP 7.3+

You still had better check that the array is not empty though, or you will get an error:

Источник

array_values

(PHP 4, PHP 5, PHP 7, PHP 8)

array_values — Выбирает все значения массива

Описание

Список параметров

Возвращаемые значения

Возвращает индексированный массив значений.

Примеры

Пример #1 Пример использования array_values()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 25 notes

Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:

Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

Doing this will cause PHP exceeds the momory limits:

Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).

echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>

If you are looking for a way to count the total number of times a specific value appears in array, use this function:

I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.

Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>

A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298

same array_flatten function, compressed and preserving keys.

/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/

Non-recursive simplest array_flatten.

A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:

The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) <
$temp = array();

Hopefully this will assist.

Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/

Источник

array_shift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_shift — Извлекает первый элемент массива

Описание

array_shift() извлекает первое значение массива array и возвращает его, сокращая размер array на один элемент. Все числовые ключи будут изменены таким образом, что нумерация массива начнётся с нуля, в то время как строковые ключи останутся прежними.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

Возвращаемые значения

Примеры

Пример #1 Пример использования array_shift()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 30 notes

Using array_shift over larger array was fairly slow. It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn’t need to reindex the array and will preserve keys if you want it to (didn’t matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop. It also requires sequential numeric keys.

Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me 😉

Here is a little function if you would like to get the top element and rotate the array afterwards.

As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn’t return the first element by reference. This may seem like very unexpected behaviour. If you’re working with a collection of references (in my case XML Nodes) this should do the trick.

class ArrayShiftReferenceTest extends UnitTestCase
<

For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

This function will save the key values of an array, and it will work in lower versions of PHP:

To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

//———————————————————-
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//———————————————————-

If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array

Here’s a utility function to parse command line arguments.

/**
* CommandLine class
*
* @package Framework
*/
/**
* Command Line Interface (CLI) utility class.
*
* @author Patrick Fisher

* @since August 21, 2009
* @package Framework
* @subpackage Env
*/
class CommandLine <

/**
* PARSE ARGUMENTS
*
* [pfisher

Источник

How to Get the First Element of an Array in PHP?

Analysis and round-up of various techniques to get the first element of a PHP array

Get First Element of an Array With Sequential Numeric Indexes

It’s fairly easy and straightforward to get the first element of a sequential array in PHP. Consider for example the following array:

Accessing the First Element of Array Directly:

Using list() :

Get First Element of an Out-Of-Order or Non-Sequential Array

In PHP, there are a number of ways you could access the value of the first element of an out-of-order (or non-sequential) array. Please note that we’ll be using the following array for all the examples that follow:

Using reset() :

The PHP reset() function not only resets the internal pointer of the array to the start of the array, but also returns the first array element, or false if the array is empty. This method has a simple syntax and support for older PHP versions:

Be careful when resetting the array pointer as each array only has one internal pointer and you may not always want to reset it to point to the start of the array.

Without Resetting the Original Array:

If you do not wish to reset the internal pointer of the array, you can work around it by creating a copy of the array simply by assigning it to a new variable before the reset() function is called, like so:

As you can see from the results, we’ve obtained the first element of the array without affecting the original.

Using array_slice() :

The advantage to using this approach is that it doesn’t modify the original array. However, on the flip side there could potentially be an array offset problem when the input array is empty. To resolve that, since our array only has one element, we could use the following methods to return the first (also the only) element:

Using array_values() :

This method may only be useful if the array is known to not be empty.

Using array_reverse() :

Using foreach Loop:

We can simply make use of the foreach loop to go one round and immediately break (or return ) after we get the first value of the array. Consider the code below:

Although it takes up a few lines of code, this would be the fastest way as it’s using the language construct foreach rather than a function call (which is more expensive).

This could be written as a reusable function as well:

Hope you found this post useful. It was published 28 Jul, 2016 (and was last revised 31 May, 2020 ). Please show your love and support by sharing this post.

Источник

Функции для работы с массивами

Содержание

User Contributed Notes 14 notes

A simple trick that can help you to guess what diff/intersect or sort function does by name.

Example: array_diff_assoc, array_intersect_assoc.

Example: array_diff_key, array_intersect_key.

Example: array_diff, array_intersect.

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

Example: arsort, asort.

Example: uksort, ksort.

Example: rsort, krsort.

Example: usort, uasort.

?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>

Updated code of ‘indioeuropeo’ with option to input string-based keys.

Here is a function to find out the maximum depth of a multidimensional array.

// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

Short function for making a recursive array copy while cloning objects on the way.

If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.

Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.

While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *