Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Array Problems

When I refresh the page displaying the products, I get the following error message on my list items:

Notice: Array to string conversion in C:\xampp\htdocs\trousers.php on line 58 Array

The line of code it is referring to is this:

            <ul>
                <?php foreach ($products as $product) { ?>
                <li><?php echo $product; ?></li>
                <?php } ?>
            </ul>

with line 58 being the li. Any ideas?

2 Answers

Here is the full page of code:

<?php

$products = array();
$products[101] = array(
    "name" => "Blue Chequered Trousers",
    "img" => "img/trousers/blue-chequered-trousers.jpg",
    "price" => 40
);
$products[102] = array(
    "name" => "Grey Trousers",
    "img" => "img/trousers/grey-trousers.jpg",
    "price" => 45
);
$products[103] = array(
    "name" => "Red trousers",
    "img" => "img/trousers/red-trousers.jpg",
    "price" => 35
);
$products[104] = array(
    "name" => "Yellow Trousers",
    "img" => "img/trousers/yellow-trousers.jpg",
    "price" => 30
);
$products[105] = array(
    "name" => "Green Trousers",
    "img" => "img/trousers/green-trousers.jpg",
    "price" => 37
);
$products[106] = array(
    "name" => "Brown Trousers",
    "img" => "img/trousers/brown-trousers.jpg",
    "price" => 39
);
$products[107] = array(
    "name" => "Pink-Chequered Trousers",
    "img" => "img/trousers/pink-chequered-trousers.jpg",
    "price" => 42
);
$products[108] = array(
    "name" => "Yellow-Striped Trousers",
    "img" => "img/trousers/yellow-striped-trousers.jpg",
    "price" => 43
);

?><?php 
$pageTitle = "Trousers";
$section = "trousers";
include('inc/header.php'); ?>

    <div class="content">

        <div class="content-container">

            <h1>TROUSERS</h1>

            <ul>
                <?php foreach ($products as $product) { ?>
                <li><?php echo $product; ?></li>
                <?php } ?>
            </ul>

        </div>

    </div>

<?php include ('inc/footer.php'); ?>

Each "$product" element is another array. To access the strings inside that array you can do <?php echo $product['name']; ?> for example to access the names.