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
CodePudding user response:
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);
}
}
CodePudding user response:
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--;
}
}