akmur
akmur

Reputation: 1635

Foreach loop returning one letter only

I am learning PHP basics and there is a problem I cannot quite understand.

I am trying to fetch some articles

$result = mysqli_query($link, 'SELECT id, title, url FROM articles');
while ($row = mysqli_fetch_array($result)) {
    $articles[] = $row['title'];
}

and I want to output the title

foreach ($articles as $a) {
    echo $a['title'];
}

Actually it is just outputting the first letter of the titles. My titles are "test" and "another test" and I just see "t" and "a" as an output.

What's wrong?

Upvotes: 0

Views: 241

Answers (2)

jay.jivani
jay.jivani

Reputation: 1574

After first loop just use

echo "<pre>";
print_r($articles);
echo "</pre>";

and then use

foreach($articles as $a) {
    echo $a;
}

Upvotes: 1

Jordi Kroon
Jordi Kroon

Reputation: 2597

That is because you are storing the value of the element 'title' in a new array. You could do 2 things:

  • Just print $a
  • Store $row in a new array

That means in your while loop, replace:

$articles[] = $row['title'];

By

$articles[] = $row;

Upvotes: 1

Related Questions