0

I am trying to print out two dimensional arrays from the results of an sql statement in php

so far i have this code

for ($i=0; $i < count($searchResults); $i++) {
print "<tr>";
print "<td>";
print "$searchResults[$i]['username']";
print "</td>";
print "<td>";
print "<a href=\"viewprofile.php?email=$searchResults[$i]['email'] 
     \">$searchResults[$i]['email']</a>";
print "</td>";
print "</tr>";
  }

but instead of printing out the value in the array it prints out things like $array['username'] instead and i dont want to use for each loops since the second condition has to be a link any ideas?

1
  • 1
    Use a foreach Commented Nov 26, 2012 at 4:17

3 Answers 3

1

You can't do multidimensional arrays in a string the way you are doing it:

print "$searchResults[$i]['username']";
print "<a href=\"viewprofile.php?email=$searchResults[$i]['email'] 
 \">$searchResults[$i]['email']</a>";

Change them to this:

print $searchResults[$i]['username'];
print "<a href=\"viewprofile.php?email=".$searchResults[$i]['email']." 
 \">".$searchResults[$i]['email']."</a>";
Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($searchResults as $result) {
    print "<tr>";
    print "<td>";
    print $result['username'];
    print "</td>";
    print "<td>";
    print "<a href=\"viewprofile.php?email=$result[email] 
         \">$result[email]</a>";
    print "</td>";
   print "</tr>";
}

Note that when embedding an array variable inside a " " string, you dont single quote escape the array keys. ($result[email] instead of $result['email']).

Comments

0

It's having problems parsing array syntax. Just take out the double quotes

print $searchResults[$i]['username'];
print "<a href=\"viewprofile.php?email=" . $searchResults[$i]['email'] .
     "\">" . $searchResults[$i]['email'] . "</a>";

If you insist on having PHP parse, read more on string parsing http://php.net/manual/en/language.types.string.php

For array syntax, you don't need the quotes, eg

print "{$searchResults[$i][username]}";

(notice no quotes around 'username'). Don't work with variables though, unless you use those curly braces (again just read up). Better to just use concat

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.