Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
PHP Foreach in Foreach with if statement

I am writing a web and i got stuck. PHP is not my language of choice, so I'm not that used to it. But lets look at the problem:

$i = 1;
$n = 0;
<div class="hs_client_logo_slider">
<?php
foreach ($hashone_client_logo_image as $hashone_client_logo_image_single) {
  foreach ($hashone_logo_list as $hashone_logo_url) {       
    if ($i > $n) {
      ?>
      <a target="_blank" href="<?php echo esc_url($hashone_logo_url) ?>"> 
        <img alt="<?php _e('logo','hashone') ?>" src="<?php echo esc_url(wp_get_attachment_url($hashone_client_logo_image_single)); ?>">
      </a>
      <?php
      $n = $n + 1;
      continue 2;
    } else {
        $i = $i + 1;
        continue 1;

Basically I am trying to do:

Foreach (x as y) && Foreach (a as b) {
  /* Magic happens here */

In the first foreach I have images and in the second one links. And for the first image I need the first link stored in logo_list, for the second image I need second link and so on... So I tried If statement that could take care of it, but for some reason it doesn't work.

Now it gives me first image with first link, but every image after that is stuck with second link. Do you have any idea what to do?

I'm glad for everyone who tries to help me out. Thank you very much.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try a different approach. First of all, prepare your data before passing it to foreach loop that is responsible for generating view, then your foreach loop will be much easier to read and maintain.

If every 1st element should go with 1st element in the second foreach, 2nd to 2nd, 3rd to 3rd and so on, then using two foreach loops is redundant. Use only 1 foreach and in every foreach iteration take its index (it can be a separate incremented variable) and take element from second array by index. You can also use a standard for loop and it should be even simpler to implement.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!