0

I want to echo [id] from my array foreach div, but when i run my code it only displays ";" in each div.

Here is my PHP:

<div class="hidden-navigation" style="display:none;">
    <?php foreach ($searchResultIDs as $key -> $nav) { ?>
        <div class='navigation-item'><?php echo $nav["id"]; ?></div>;
    <?php } ?>
</div>

Here is my array:

Array
(
[0] => stdClass Object
    (
        [active] => 1
        [id] => 9839
    )

[1] => stdClass Object
    (
        [active] => 
        [id] => 66150
    )

[2] => stdClass Object
    (
        [active] => 
        [id] => 66444
    )

[3] => stdClass Object
    (
        [active] => 
        [id] => 67554
    )
)
2
  • foreach ($searchResultIDs as $nav) Commented Jan 10, 2018 at 10:29
  • You can use my function posted here to turn your stdClass Object into an array or vice versa for easier manageability. Commented Jun 24, 2022 at 1:58

4 Answers 4

3

your array is stdClass Object. you should get value like this. and also -> replace with this =>

 echo $nav->id;

Complete code is:

<div class="hidden-navigation" style="display:none;">
    <?php foreach ($searchResultIDs as $nav) { ?>
        <div class='navigation-item'><?php echo $nav->id; ?></div>;
    <?php } ?>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

you should accept correct answer. in future your question is help to other users
2

Try this

<?php foreach ($searchResultIDs as $nav) { ?>
     <div class='navigation-item'><?php echo $nav->id; ?></div>;
<?php } ?>

$nav hasobjects so you can echo by using ->

Comments

0

The foreach syntax is wrong, it should be => instead of ->:

foreach ($searchResultIDs as $key => $nav)

Also $nav is an object, so do $nav->id instead of $nav['id'].

Comments

0

You can try in these different ways

Step 1:

<div class="hidden-navigation" style="display:none;">
    <?php foreach ($searchResultIDs as  $nav) { ?>
        <div class='navigation-item'><?php echo $nav["id"]; ?></div>;
    <?php } ?>
</div>

Step 2:

<div class="hidden-navigation" style="display:none;">
    <?php foreach ($searchResultIDs as $key => $nav) { ?>
        <div class='navigation-item'><?php echo $nav->id; ?></div>;
    <?php } ?>
</div>

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.