0

I have an array full of associative arrays like so:

$arr = [
  ['title' => 'My title', 'content' => 'lorem ...', comments: 'lorem ipsum'],
  ['title' => 'My title 2', 'content' => 'lorem ...'],
  ['title' => 'My title 3', 'content' => 'lorem ...'],
  ['title' => 'My title 4', 'content' => 'lorem ...', comments: 'lorem ipsum'],
];

As you can see, some of them don't have comments.

The problem is, I have then a foreach loop like this:

<?php foreach($arr as $key => $value){
  extract($value);
?>
  <div>
    ...etc
    <?php if($comment): ?>
       <span><?= $comment ?></span>
    <?php endif; ?>
  </div>
<?php } ?>

In the second iteration, the variable $comments now holds the value of the first item in the array, cause it doesn't find the property in the associative array and it uses the last one, breaking the if statement.

Is there any way to avoid this without having to add a comments: null or something to the original array?

7
  • 7
    Doesn’t use extract. Properly name your variables. Your IDE will also be happy about that. Commented Jun 12, 2020 at 18:39
  • 2
    if (isset($value['comment'])) { ... } Commented Jun 12, 2020 at 18:43
  • 2
    In PHP variables are scoped to the function, not the iteration block. So a variable set in a loop doesn't go away when the loop repeats. Commented Jun 12, 2020 at 18:50
  • 2
    Do not use extract(). You don't need it. Ever. Commented Jun 12, 2020 at 20:49
  • 1
    @axiac not necessary. extract(), when ̶c̶o̶r̶r̶e̶c̶t̶l̶y̶ used, leads quickly to a code impossible to maintain, and therefore, grants a lifetime job Commented Jun 13, 2020 at 6:15

1 Answer 1

2

Simply use isset to check if variable $elem['comments'] exists:

<div>
<?php
foreach($arr as $key => $elem){
    if(isset($elem['comments'])){
        // Comments exists here
        echo "<span>".$elem['comments']."</span>";
    }else{
        // Comments do not exists here, so don't echo anything
    }
}
?>
</div>

Or use array_key_exists to check if comments key is in array elem:

<?php
foreach($arr as $key => $elem){
    if(array_key_exists('comments', $elem)) {
        // Comments exists here
        echo "<span>".$elem['comments']."</span>";
    }else{
        // Comments do not exists here, so don't echo anything
    }
}
?>

Take notice that:

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

So in your use case I would recommend you to use isset as you discard existing comments keys with null values the same way as if comments keys do not exists.

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.