-1

I am working on a comment system and I want to show only 3 results, then I will load the rest on the other side but here I can't think of how to get only 3.

The values come from a form and I save them in a post goal creating an array.

I show how I get the comments:


$datacomments = array_reverse(get_post_meta($product_id, 'propina5', false)); 

foreach ($datacomments as $infocalif){

$comment = $infocalif['comment'];

echo $comment;
}

The array:

echo print_r($datacomments);

Array ( [0] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[1] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[2] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[3] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[4] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) ) 1

By default this is how I get all the comments saved in the meta, but I only want to get 3, it will be the last 3 due to array_reverse.

Then I will load everything in a different template so as not to delay the initial load

Any suggestion?

mario
  • 47
  • 6
  • 1
    Yes, excellent!!! I delete this question so that it is not duplicated? @OMiShah – mario Dec 01 '21 at 04:44
  • Yes, if you don't do then this question will be marked duplicate and closed by a moderator. – OMi Shah Dec 01 '21 at 04:46
  • Thanks, I am very new to this but someone responded with another approach and it is correct too. So this question now I don't think it can be removed. Leave it as it is? – mario Dec 01 '21 at 04:49

1 Answers1

1

Use counter

$cnt = 2;
foreach ($datacomments as $infocalif) {
    $comment = $infocalif['comment'];
    echo $comment;
    
    if (!$cnt--) break;
}
unclexo
  • 3,691
  • 2
  • 18
  • 26
diavolic
  • 722
  • 1
  • 4
  • 5
  • Thank you!! Your answer is correct and gives me another approach. I will mark it now. @diavolic – mario Dec 01 '21 at 04:47
  • 1
    you can also use https://www.php.net/manual/en/function.array-slice.php, more complicated but more beautiful – diavolic Dec 01 '21 at 04:48