php array next element
next element in a associative php array
This seems so easy but i cant figure it out
I need to get the next element in the array but i cant figure it out. so for example
I need to return matt@someplace.com and if Its
i need start from the top and return spence@someplace.com
but they dont return what i am expecting
3 Answers 3
Reset() rewind the array pointer to the first element, each() returns the current element key and value as an array then move to the next element.
Or you can use foreach if you loop over all of them
You could do something like this:
However I think you might have an error in your logic and what you are doing can be done better, such as using a foreach loop.
You would be better storing these in an indexed array to achieve the functionality you’re looking for
Not the answer you’re looking for? Browse other questions tagged php loops or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Php array next element
(PHP 4, PHP 5, PHP 7, PHP 8)
next — Перемещает указатель массива вперёд на один элемент
Описание
Список параметров
Массив ( array ), изменяемый данной функцией.
Возвращаемые значения
Примеры
Пример #1 Пример использования next() и связанных функций
Примечания
Смотрите также
User Contributed Notes 16 notes
Now from PHP 7.2, the function «each» is deprecated, so the has_next I’ve posted is no longer a good idea. There is another to keep it simple and fast:
Don’t confuse next with continue!
If you’re a Perl developer starting with PHP, you might try to use «next» inside a loop to skip to the next iteration.
The php compiler will take next. but it’s not going to work.
Papipo’s function below is usefull in concept but does not work.
«Since you do not pass the array by reference, its pointer is only moved inside the function.»
This is true, but the array you are manipulating in your has_next() function will have it’s pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a «next» element.
Try the followig insetad:
This code returns neighbors of the specified key. The result will be empty if it doesn’t have any neighbors. My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array. Feel free to point out stupidities 🙂
I need to know if an array has more items, but without moving array’s internail pointer. Thats is, a has_next() function:
// prints ‘melon’
?>
Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of ‘work arounds’.
foreach($array as &$value)
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array’s internal pointer. This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element. You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.
This function returns next element in array after your key or false if it last or key doesn’t exists in array.
a more readable version of papipo’s has_next function:
brentimus’ array_set_pointer function will only work if the array value is unique in the array, and none of the array values are FALSE. It would be more reliable to use key() instead of current(). For similar reasons it’s better to check key() after calling next() to determine whether the next() element «exists». Simply checking the value returned by next() will produce a false negative when looking at, for example, the first element of the array: [‘one’, 0, ‘three’]
However, it also turns out that the copied array retains the original array’s pointer, so array_set_pointer is not actually required here. The following should work:
This class implements simple operations with array
public function __construct () <
public function getCurrent () <
public function getNext () <
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know
function Cycle()
<
$this->dataArray = func_get_args();
$this->dataArrayCount = count($this->dataArray);
>
$bgColor = new Cycle(‘#000000’, ‘#FFFFFF’, ‘#FF0000’);
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Создаёт массив
Описание
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Этот пример создаёт массив, нумерация которого начинается с 1.
Результат выполнения данного примера:
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
Примечания
Смотрите также
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
Here’s a further example:
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
Get next element in foreach loop
I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I’ve read about the current and next functions but I can’t figure out how to use them.
9 Answers 9
A unique approach would be to reverse the array and then loop. This will work for non-numerically indexed arrays as well:
If you are still interested in using the current and next functions, you could do this:
You could probably use while loop instead of foreach:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don’t rely on the array pointer during or after the foreach without resetting it.
If the indexes are continuous:
You could get the keys/values and index
if its numerically indexed:
The general solution could be a caching iterator. A properly implemented caching iterator works with any Iterator, and saves memory. PHP SPL has a CachingIterator, but it is very odd, and has very limited functionality. However, you can write your own lookahead iterator like this:
You could get the keys of the array before the foreach, then use a counter to check the next element, something like:
A foreach loop in php will iterate over a copy of the original array, making next() and prev() functions useless. If you have an associative array and need to fetch the next item, you could iterate over the array keys instead:
Since the resulting array of keys has a continuous index itself, you can use that instead to access the original array.
Using method 2 the complete foreach could look like this:
PHP get previous array element knowing current array key
I have an array with specific keys:
9 Answers 9
Then you can use prev() :
Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.
If the key does not exist in the array, you have an infinite loop, but this could be solved with:
of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.
Solution with fast lookups: (if you have to do this more than once)
I solved this issue in this way:
@return previous key or false if no previous key is available
@Luca Borrione’s solution was helpful. If you want to find both previous and next keys, you may use the following function:
You can iterate through the array in reverse and return the next iteration after finding the search value.
Just iterate over the array
An alternative solution is to get the keys of your array within an enumerated array like so:
as the keys array is index you can move the the previous key like so:
key we have our previous key to get the value from the original array
This is a simple solution for taking previous and next items, even if we are at the ends of the array.
Expanding further on the solution of Luca Borrione and cenk, so that you can wrap around the end of the array in either direction, you may use:
If your data is large then it might be a best practice to avoid looping. You could make your own custom function, like so:
Note that if you provide first key then it will return the last value, like a cyclic array. You can handle it however you like.
With a bit tweak, you can also generalize it to return next values.
As for why prev isnt working is because it isnt used for that purpose. It just sets the internal pointer of the array to one behind, exact inverse of next