-1

I am trying to display an image, where the path is defined in an array not from a database.

First index.php calls app/app.php, which then includes the $animals array from animals.php.

The problem is how do I access $animals in index.php and get the value of the pics key?

index.php

<?php require_once __DIR__ . '/app/app.php';
    //var_dump($animals);?>
<?php foreach ($animals as $animal): ?> <br>
    <a href="#"><?php echo $animal['name'] ?></a> 
    <?php echo $animal['size'] ?>
    <img src="<?php echo $animal['pics'] ?>" alt="Pic 1">
    <?php //echo "<img src='" . $pics . "' alt=''>";  ?>
<?php endforeach; ?>

app/app.php:

<?php

ini_set('display_errors', '1');
error_reporting('E_ALL');
$animals = require_once __DIR__ . '/Db/animals.php';

animals.php:

<?php

return [
    [
        'name' => 'cow',
        'size' => 20,
        'pics' => ['/photos/cow1.jpg'],
         //'pics' => 'photos/cow1.jpg',
         //'pics' => '<img class="wrap" src="photos/cow1.jpg">',
         //'pics' => './photos/cow1.jpg';
         'detailes' => [
             'colour' => 'brown',
             'origin' => 'N Italy',
         ],
    ],
];

It's frustrating that I can't solve it. Maybe someone could help.

3
  • 2
    pics is a sub array, so $animal['pics'][0] is the first one Commented May 29, 2018 at 21:46
  • 2
    var_dump is your friend. Maybe with xdebug for pretty output. Good to get in habit of deciphering those dumps. Commented May 29, 2018 at 21:49
  • Thanks Smith. I ask you if I defined corectly 'pics' in animals.php? Commented May 29, 2018 at 21:54

1 Answer 1

0

See if this helps...

array(1) {
  [0]=>
  array(4) {
    ["name"]=>
    string(3) "cow"
    ["size"]=>
    int(20)
    ["pics"]=>
    array(1) {
      [0]=>
      string(16) "/photos/cow1.jpg"
    }
    ["detailes"]=>
    array(2) {
      ["colour"]=>
      string(5) "brown"
      ["origin"]=>
      string(7) "N Italy"
    }
  }
}

You actually want: echo $a[0]['pics'][0];

Arrays, inside arrays. It does get confusing but will fast become second nature to work with.

Play around with var_dump...

var_dump($a);
var_dump($a[0]);
etc...

or try iterating when stumped...

foreach ($a as $key => $value) {
 echo "$key -> $value";
}

That would result in NOTICE Array to string conversion because $value is an array. Try adding a second (nested) foreach loop. When you can iterate over the entire array you know you understand it... see also: is_array and recursion.

Sign up to request clarification or add additional context in comments.

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.