PHP For Loop

When you need to do the same script many times, for exemple you want to send emails to all your users, you don't need to write a php code for each user, you just need to use for Loop which will do it for each one.
This is how:
<?php
for ($userid=1;$userid<=10;$userid++){
send_email($userid);
}
?>

Where send_email() is your own function that send the email to the user with the id as parameter.

Another exemple to For Loop, let's say you want to count 1+2x2+3x3+...+nxn, this is how you can do it:
<?php
$n=10;
$t=0;
for ($i=1;$i<=$n;$i++){
$t+=$i*$i; // the same as $t=$t+$i*$i
}
?>


So how For loop works ?

1. Set a counter variable to some initial value (i.e $i=0).
2. Check to see if the conditional statement is true(i.e $i<=10).
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop(i.e $i++, or $i+=1, ou $i=$i+1) .

And this is how to do it:
for ( initialize a counter; conditional statement; increment a counter){
do this code;
}


The php loop will help you a lot in php programming, and there are other ways to do loops other that For, like while.

44 comments:

Custom-Web-design said...

Great work...if you can give another example then it would be more easy to understand.

Cegonsoft said...

It's a nice example..

Jack said...

Quite worthwhile info, thank you for the article.
sex in office | cast aluminum | Toronto condos

Unknown said...

Our dedicated PHP Programmers have an appropriate mix of expertise and ability that gives you the choice to select most suitable professional/team for your project.

Unknown said...

This is the best blog design and article. Very nice job. Thank you very much
Your design and pics of the blog is really nice.

php training

Pasang Iklan Gratis said...

It's really useful for me, thanks a lot.

Unknown said...

Thanks for this informative blog. Good information about PHP loop. keep sharing nice blog. Best PHP training in Bangalore

Garrick Co Ida said...

PHP Training in Chennai
PHP Online Training India

Aptron said...

It's a nice example of PHP loop and that's a important part of PHP Course.

Naveen Yadav said...

Salesforce Admin Certification Training Gurgaon,Delhi

Ancy merina said...
This comment has been removed by the author.
Saravanan said...

Language Interpretation Services, Voice Over Services India

Unknown said...

I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
Data science training in tambaram
Data science training in kalyan nagar
Data Science training in OMR
Data Science training in anna nagar
Data Science training in chennai
Data Science training in marathahalli
Data Science training in BTM layout
Data Science training in rajaji nagar

nilashri said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...

Deops training in annanagar

Devops training in chennai

Devops training in marathahalli

Devops training in rajajinagar

Devops training in BTM Layout

nivatha said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
Devops training in Chennai
Devops training in Bangalore
Devops training in Pune
Devops Online training
Devops training in Pune
Devops training in Bangalore
Devops training in tambaram

simbu said...

I simply want to give you a huge thumbs up for the great info you have got here on this post.



java training in chennai | java training in bangalore

java online training | java training in pune

selenium training in chennai

selenium training in bangalore

Anonymous said...

This is good site and nice point of view.I learnt lots of useful information.
angularjs online Training

angularjs Training in marathahalli

angularjs interview questions and answers

angularjs Training in bangalore

angularjs Training in bangalore

angularjs Training in chennai

rohini said...

" I enjoy what you guys are usually up too. This sort of clever work and coverage! Keep up the wonderful works guys I’ve added you guys to my blog roll.
"
iWatch service center chennai | apple ipad service center in chennai | apple iphone service center in chennai | Apple laptop service center in chennai

rohini said...

"Hello! Someone in my Facebook group shared this website with us, so I came to give it a look. I’m enjoying the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and amazing design and style.
"
iWatch service center chennai | apple ipad service center in chennai | apple iphone service center in chennai

rohini said...

Your lessons have been very insightful and fun!
Acer service centre in Chennai | acer mobile service center in chennai | acer laptop service center in chennai | acer laptop service center in chennai | Acer service centre in Chennai | acer services in chennai | Acer service centre in Chennai | acer laptop service center in chennai

Anonymous said...

Thanks writer.For emphasizing this, we hope you can share more knowledge, regards!
Authorized apple service center in Chennai | apple service center in chennai | Authorized apple service center in Chennai | apple service center in chennai | Mobile service center in chennai | iphone water damage service in chennai

rohini said...

I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the net and meeting techniques that were not productive, I thought my life was done.
iphone display replacement service in chennai | iphone service center in chennai | iphone unlocking service in chennai | Authorized iphone service center in Chennai | iphone service center in chennai

Madeline said...


Thanks for sharing such a useful and informative post like this. Keep updating more updates like this.
Apple iPhone Service Center in Chennai Anna Nagar


Eva.William said...
This comment has been removed by the author.
Vennala said...
This comment has been removed by the author.
Aadhya said...
This comment has been removed by the author.
Anonymous said...

С сумкой для девушек всё не так просто. Для женщины на первое место выходит то, как выглядит атрибут. Девушка готова потратить некоторое время, чтобы привязаться к необычной для себя вещи в гардеробчике, но несмотря ни на что произвести впечатление на коллег. В сумочке женщины можно отыскать записную книжку, ежедневник, приспособления для волос. Перечень может быть намного больше, всё упираеться от параметра предпочтенного атрибута. В гардеробчике мисс одновременно много аксессуаров разных форм, расцветок и стилей. Для посещения на работу или учёбу леди избирает большую сумочку или клатч, для явки с друзьями вечером. Любопытно, что женщине редко даруют сумку. Атрибуты дама выбирает единолично, а если есть нужда, то демонстрирует подругам то, что она предпочитает в атрибуте ожидающего подарка. Подарки и спонтанные покупки здесь будут ненужны. Покупка инной аксессуара – это важное дело, но черезмерно увлекательное. Поэтому осуществляйте это часто тут сумки италия !

Vishali said...

Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
Artificial Intelligence Online Training
Java Online Training
AWS Online Training
Machine Learning Online Training
Data Science Online Training
DevOps Online Training

rocky said...

I read more useful article. Nice content.
Python Training in Chennai

Python Training in Training

Python Training in Bangalore
Python Hyderabad

Python Training in Coimbatore


Anonymous said...

Невероятно познавательные и невероятно правдивые онлайн гадания для уточнении загадывания нашего будущего: это именно то, что вы увидите на страницах нашего сайта. Гадание да-нет онлайн бесплатно, правдивое является самым быстрым и простым вариантом для получения нужных информаций из эфирного поля нашей планеты.

James Williams said...

Great Post, thanks for sharing the informative information.
PHP Online Training
PHP Online Course
PHP Online Training in chennai

Anonymous said...

Каждый клиент, покупая плитку Alfa Ceramiche в интернет-магазине Реал Грес, получает в самом деле классный товар. Ради того чтобы купить плитку в магазине РеалГрес, нужно просто просмотреть официальный сайт производителя. Отделывают стенки и полы керамогранитом существенным образом ради её физических особенностей. Ровная и гладкая поверхность довольно легко протирается.

Anonymous said...

Воспользуйтесь наибольшими преимуществами исключительно здесь бетонные вазоны купить в липецке. Огромный количество оборудования для жилищной сферы. Ниже представлены самые важные плюсы взаимодействия с данной компанией.

Anonymous said...

Топовый агрегатор подборки микрофинансовых продуктов позволяет приобрести требующийся микрокредит. Занять большую сумму на карточку на удивление не сложно. Cashtoyou займ – это гарантированный метод получить деньги в короткие сроки.

Anonymous said...

Бонусный счет позволяет заработать немало денег. Пройдите регистрацию на платформе и увидите дополнительные очки в своей учетке. Необходимо помнить, что сервис казино икс casino x зеркало дарит всем геймерам дополнительные бонусы.

Anonymous said...

Только лишь на портале mr bit casino отзывы реальных игроков пользователи легко найдут понравившуюся онлайн-игру для отдыха. Наведавшись в игровой клуб, вы сможете окунуться в любопытные приключения. Отрываться с единомышленниками в значительной степени интереснее, чем самому дома.

Anonymous said...

Для ознакомления с порталом реализован тестовый счет. На сайте joycasino вывод денег отзывы представлено максимальное число игр. Серьезные ставки в игральных автоматах – это элементарный вариант отлично отдохнуть и проверить свою судьбу.

Anonymous said...

Ответственный и авторитетный импортер всегда может предоставить широкий ассортимент декоративного покрытия для ванной. Бренд sotni.ru продает gayafores boldstone уже свыше двенадцати лет.

Parul Pathak said...

This site helps to clear your all query.vikram university ba 2nd year result
vikram university ba 3rd year result This is really worth reading. nice informative article.

Ravi said...

Thank you

https://shikshaeducationconsultancy.com/colleges/lviv-national-medical-university-mbbs-in-ukraine
https://shikshaeducationconsultancy.com/colleges/bogomolets-national-medical-university-mbbs-in-ukraine
https://shikshaeducationconsultancy.com/colleges/vinnytsia-national-pirogov-medical-university-vnmu-mbbs-in-ukraine
https://shikshaeducationconsultancy.com/colleges/asian-medical-institute-asmi-mbbs-in-kyrgyzstan
https://shikshaeducationconsultancy.com/colleges/kazakh-national-medical-university-knmu-mbbs-in-kazakhstan
https://shikshaeducationconsultancy.com/colleges/international-higher-school-of-medicine-ism-mbbs-in-kyrgyzstan

https://shikshaeducationconsultancy.com/colleges/kyrgyz-state-medical-academy-ksma-mbbs-in-kyrgyzstan
https://shikshaeducationconsultancy.com/colleges/medical-college-for-women-and-hospital-mbbs-in-bangladesh
https://shikshaeducationconsultancy.com/colleges/osh-medical-university-oshmu-mbbs-in-kyrgyzstan
https://shikshaeducationconsultancy.com/colleges/jalal-abad-state-university-jasu-mbbs-in-kyrgyzstan

Ravi said...

Thank you for information

R Programming Training
MIS Training
HTML,CSS,JQuery Training
Web Designing Training
Data Analytics Trainingp
SAS Training
WordPress Training
PHP Training
Python Training

Ravi said...

Nice information


PHP training ghaziabad
R programming training delhi
Python training in delhi
Python training noida
Free python course
R Programming Training noida
Data Analytics Training Delhi
Data Analytics Training Noida
R programming training ghaziabad
Python training in ghaziabad
php training in delhi
php training in noida
open source web development course
full stack web development course



Anonymous said...

nice post. great thoughts.
MBBS in Bangladesh

Government Jobs in Punjab said...

I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the internet will be much more useful than ever before.

mdsu ba 2nd year result 2022 roll number wise