php foreach last item
PHP: Find the last item in a nested foreach loop?
I’m working with an API to retrieve records based on user input.
There are filters and filter groups that will be concatenated, however, I do not want the last AND or OR in the nested for each loop to be concatenated to the string.
I would like to have an if statement that looks for the last item in the nested foreach loop and concatenates a different string to the end, like this:
What is the best practice for finding the last item of a nested for each loop using PHP?
Here is the reference code:
Here is an example of a request, the two objects are combined in the foreach loop:
Here an example of the current output:
I would like it to output:
3 Answers 3
Just an idea: you can always understand if the current iteration is the first (by using a flag).
In this way, you can:
You could try adapting this solution to your needs.
I shall work under these assumptions:
If this is so, then you can use a limited state machine to achieve your result:
Using this version of your request,
the result is the following, valid SQL:
(if the destination language is not SQL then the code can be changed slightly, of course).
a more refined result (PDO support)
Normally you do not want to include the request strings in your SQL code as is, because this allows the user to arbitrarily alter the SQL code you will execute. For example if I were to send along a tag of
To avoid this we use PDO and SQL parameterization. This requires sending the query in two parts, a prepared query like
Как определить первую и последнюю итерации в цикле foreach?
вопрос простой. У меня есть foreach цикл в моем коде:
в этом цикле я хочу реагировать по-разному, когда мы находимся в первой или последней итерации.
18 ответов:
вы можете использовать счетчик:
Если вы предпочитаете решение, которое не требует инициализации счетчика вне цикла, я предлагаю сравнить текущий ключ итерации с функцией, которая сообщает вам последний / первый ключ массива.
это становится несколько более эффективным (и более читаемым) с предстоящим PHP 7.3.
решение для PHP 7.3 и выше:
решение для всех версий PHP:
, чтобы найти последний элемент, я нашел этот кусок кода работает каждый раз:
более упрощенная версия выше и если вы не используете пользовательские индексы.
Версия 2-потому что я пришел к ненависти, используя остальное, если это не необходимо.
вы можете удалить первый и последний элементы из массива и обрабатывать их отдельно.
Вот так:
удаление всего форматирования в CSS вместо встроенных тегов улучшит ваш код и ускорит время загрузки.
вы также можете избежать смешивания HTML с логикой php, когда это возможно.
Ваша страница может быть сделана намного более читаемой и поддерживаемой, разделяя такие вещи:
1: Почему бы не использовать простой for заявление? Предполагая, что вы используете реальный массив, а не Iterator вы можете легко проверить, является ли переменная счетчика 0 или одним меньше, чем все количество элементов. На мой взгляд это самое чистое и понятное решение.
2: Вы должны рассмотреть, используя Вложенные Наборы для хранения структуры дерева. Кроме того, вы можете улучшить все это с помощью рекурсивной функции.
для сценариев генерации SQL-запросов или всего, что выполняет другое действие для первого или последнего элемента, это намного быстрее (почти в два раза быстрее), чтобы избежать использования ненужных проверок переменных.
текущее принятое решение использует цикл и проверку в цикле, которая будет выполнена every_single_iteration, правильный (быстрый) способ сделать это следующим образом :
небольшой самодельный бенчмарк показал следующее:
тест1: 100000 работает модели морг
время: 1869.3430423737 миллисекунд
test2: 100000 запусков модели, если последний
время: 3235.6359958649 миллисекунд
и таким образом совершенно ясно, что проверка стоит много, и, конечно, она становится еще хуже, чем больше переменных проверок вы добавляете 😉
The array_keys функцию можно использовать для того чтобы сделать эффективную работу ответа как foreach :
Я не делал бенчмаркинг на этом, но никакая логика не была добавлена к циклу, который был самым большим ударом по производительности, поэтому я подозреваю, что тесты, предоставленные с эффективным ответом, довольно близки.
если ты хочешь functionalize такого рода вещи, я замахнулся на такой функция iterateList здесь. Хотя, возможно, вы захотите проверить код gist, если вы очень обеспокоены об эффективности. Я не уверен, сколько накладных расходов вводит весь вызов функции.
и я предпочитаю использовать for петли вместо foreach если бы я собирался использовать счетчик, как это:
Php foreach last item
You can also use the alternative syntax for the foreach cycle:
I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done:
Even though it is not mentioned in this article, you can use «break» control structure to exit from the «foreach» loop.
WARNING: Looping through «values by reference» for «extra performance» is an old myth. It’s actually WORSE!
?>
Which do you think is faster?
Lots of people think the answer is two() because it uses «reference to value, which it doesn’t have to copy each value when it loops».
Well, that’s totally wrong!
Here’s what actually happens:
Alright, so what’s the second version doing? The beloved «iterate values by reference»?
— This function takes an array as argument ($arr).
— The array function argument itself isn’t passed by reference, so the function knows it isn’t allowed to modify the original at all.
— Then the foreach loop happens. The array itself wasn’t passed by reference to the function, so PHP knows that it isn’t allowed to modify the outside array.
— But it also sees that you want to look at all VALUES by reference (&$val), so PHP says «Uh oh, this is dangerous. If we just give them references to the original array’s values, and they assign some new value to their reference, they would destroy the original array which they aren’t allowed to touch!».
— So PHP makes a FULL COPY of the ENTIRE array and ALL VALUES before it starts iterating. YIKES!
Therefore: STOP using the old, mythological «&$val» iteration method! It’s almost always BAD! With worse performance, and risks of bugs and quirks as is demonstrated in the manual.
You can always manually write array assignments explicitly, without references, like this:
PHP foreach overwrite all items with last item
I know that was ask many times but I didn’t find something related to me. I’m new to PHP and I’m learning how to use foreach right now. I got this code:
$row[‘Addr.Line2’] etc. works good, it display the information I want but only the last element. So the last element overwrites all the other elements and I don’t know why.
Can someone explain me why it is or give me a hint how to fix?
5 Answers 5
I believe you need all the values here. In that case, you add the values into an array, like so:
You might want to use an array to save your info instead:
You’re repeatedly overwriting the same variable with a new value, of course only the last one will remain after the loop. Perhaps you want to create an array instead:
It turned out every element of my array the object was saved in, that value would update when I made a change to the object.
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
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.
How to determine the first and last iteration in a foreach loop?
The question is simple. I have a foreach loop in my code:
In this loop, I want to react differently when we are in first or last iteration.
20 Answers 20
If you prefer a solution that does not require the initialization of the counter outside the loop, then you can compare the current iteration key against the function that tells you the last / first key of the array.
PHP 7.3 and newer:
PHP 7.2 and older:
You could use a counter:
To find the last item, I find this piece of code works every time:
A more simplified version of the above and presuming you’re not using custom indexes.
You could remove the first and last elements off the array and process them separately.
Removing all the formatting to CSS instead of inline tags would improve your code and speed up load time.
You could also avoid mixing HTML with php logic whenever possible.
Your page could be made a lot more readable and maintainable by separating things like this:
Thank you @billynoah for your sorting out the end issue.
An attempt to find the first would be:
1: Why not use a simple for statement? Assuming you’re using a real array and not an Iterator you could easily check whether the counter variable is 0 or one less than the whole number of elements. In my opinion this is the most clean and understandable solution.
2: You should consider using Nested Sets to store your tree structure. Additionally you can improve the whole thing by using recursive functions.
The array_keys function can be used to make the efficient answer work like foreach :
I haven’t done benchmarking on this, but no logic has been added to the loop, which is were the biggest hit to performance happens, so I’d suspect that the benchmarks provided with the efficient answer are pretty close.
If you wanted to functionalize this kind of thing, I’ve taken a swing at such an iterateList function here. Although, you might want to benchmark the gist code if you’re super concerned about efficiency. I’m not sure how much overhead all the function invocation introduces.