0

Sorry I am sure this is easy but I have spent ages trying to solve this simple problem. I have an array called $listOfLinks. When I print_r this is the output:

Array ( [0] => Array ( [LinkID] => 1 [GroupID] => 1 [Description] => Home [Title] => Home Page [Hyperlink] => [Target] => ) [1] => Array ( [LinkID] => 2 [GroupID] => 1 [Description] => View Employees [Title] => View Employees [Hyperlink] => Views/ViewEmployees.php [Target] => ) )

I want to loop through the array printing out things such as the Title. So far my code looks like this:

foreach($listOfLinks as $key => $element)
{
    echo $key["Title"];
}

Something is wrong as the output is absolutely nothing. There is no error. message or anything. I have been trying to follow the advice on http://www.tizag.com/phpT/arrays.php but I seem to have misunderstood something.

This link to Foreach loop returning null values in PHP? looked promising but it ultimately turned out to be a simple problem unrelated to mine. Also promising was PHP: Loop through multidimensional array and establish parent-child relationships between array items but it did not have a suitable solution. I thought I was close with this Simple array question in PHP but it turned out to be unrelated. This also looked promising but wasn't. PHP Yet another Multidimensional Associative Array problem.

It looks like the answer is at Another php array looping question but I don't understand it if it is there.

Please don't hate me for such a simple question. I have really been trying really hard to understand this.

0

2 Answers 2

2

When looping with the foreach syntax you used, you want to work with the $element variable (which contains the current item's data), and not the $key one (which only contains the index of the current item in the array):

foreach($listOfLinks as $key => $element)
{
    echo $element["Title"];
}

Also, as you are not using the key of each item, you can use this shorter syntax :

foreach($listOfLinks as $element)
{
    echo $element["Title"];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer @Pascal but I have awarded the tick to xbonez because he answered first and does not have nearly the reputation you did. Your answer was equally good. Hope this is fair. Thanks.
1
foreach($listOfLinks as $value)
{
    echo $value["Title"];
}

What you are doing is indexing into the key. Instead index into the array element.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.