0

I am trying to foreach multiple arrays with if condition, I have 3 arrays like below :

$contents = array('content1', 'content2', 'content3', 'content4');    
$types = array('pdf', 'pdf', 'txt', 'pdf');    
$links = array('link1', 'link2', 'link3');

foreach ($contents as $key => $value) {
            
            echo "$value<br>";
            
        if ($types[$key] == 'pdf') {
             echo "$links[$key]<br>";
        }

}

Output is like this :
content1
link1
content2
link2
content3
content4

Links array has 3 values, others 4 . I want if content type is pdf use link value there if not skip. And i want output like below:

content1
link1
content2
link2
content3
content4
link3

thanks for your help

2
  • can you change the structure of the array? if yes: you could change it to a multidimensional array. Commented Sep 15, 2021 at 18:08
  • Did you give up??? Commented Sep 23, 2021 at 14:38

2 Answers 2

1

If the arrays are not the same length then you won't be able to use the key. You could use another variable to keep track of the key needed in $links or you can advance the pointer of $links each time:

foreach ($contents as $key => $value) {
    echo "$value<br>\n";
        
    if ($types[$key] == 'pdf') {
         echo current($links) . "<br>\n";
         next($links);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In this scenario, you need to skip forward the links array so you can do it by adding an else statement. try this code

$contents = array('content1', 'content2', 'content3', 'content4');
$types = array('pdf', 'pdf', 'txt', 'pdf');
$links = array('link1', 'link2', 'link3');

$skip_links_array = 0;

foreach ($contents as $key => $value) {

    echo "$value<br>";

    if ($types[$key] == 'pdf') {
        echo $links[$key + $skip_type]."<br>";
    }else{
        $skip_type--;
    }

}

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.