1

I'm over complicating the output of this example array, what is the cleanest, most elegant way you would do this for the desired output.

Array Ex:

Array
(
    [0] => Array
        (
            [<h4><a href="#link1">Link 1</a></h4>] => <img src="Image_1.jpg" />
        )

    [1] => Array
        (
            [<h4><a href="#link2">Link 2</a></h4>] => <img src="Image_2.png" />
        )

    [2] => Array
        (
            [<h4><a href="#link3">Link 3</a></h4>] => <img src="Image_3.png" />
        )

    [3] => Array
        (
            [<h4><a href="#link3">Link 4</a></h4>] => <img src="Image_4.png" />
        )
)

Desired Output

<h4><a href="#link1">Link 1</a></h4>
<img src="Image_1.jpg" />

<h4><a href="#link2">Link 2</a></h4>
<img src="Image_2.png" />

<h4><a href="#link3">Link 3</a></h4>
<img src="Image_3.png" />

<h4><a href="#link3">Link 4</a></h4>
<img src="Image_4.png" />

Thanks for the feedback.

4
  • have you tried using $print_r(); or var_dump();? Commented Feb 5, 2016 at 9:28
  • Look up the foreach command Commented Feb 5, 2016 at 9:28
  • @SaucedApples - yeah, I'm looking for the described desired output. Commented Feb 5, 2016 at 9:34
  • @RiggsFolly - thanks, whilst I was using that, I felt I was overcomplicating it. Commented Feb 5, 2016 at 9:35

3 Answers 3

6

I think this should do what you want :

<?php

foreach ($foo as $bar) {
    foreach($bar as $title => $image) {
        echo $title;
        echo $image;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

No need for the \n.. :)
@sougata yes u r right and I see u removed your answer bro :)
@sougata yes my friend it's multidimensional
@Gwendal - perfect. Will mark as answer after the time limit.
1

You can also use array_walk

array_walk($arr, function($value,$key){
        array_walk($value, function($v,$k){
            echo $k;
            echo $v;
       });
});

Comments

0

I am new to php though i tried my best in bringing up this and i think this would work fine with the sample you provided.

<?php
$link1= '<h4><a href="#link1">Link 1</a></h4>';
$link2= '<h4><a href="#link2">Link 2</a></h4>'; 
$image1='<img src="Image_1.jpg"';
$image2='<img src="Image_2.png"';

$elements =  array("$link1"=>"$image1","$link2"=>"$image2");
foreach($elements as $ele =>$ele_value)
{
echo "link=".$ele . ", image=" . $ele_value;
echo "<br>";
}?>

2 Comments

Please see the marked answer. The array I presentenced is not something I can change. Thanks.
i got your point, but when i tried to execute the array code it throws syntax error, unexpected '<', expecting ']' , so i used variable instead in array

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.