Is it possible to get only 3 results when calling a value within a multidimensional array meta with php?

40 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

Use counter

$cnt = 2;
foreach ($datacomments as $infocalif) {
    $comment = $infocalif['comment'];
    echo $comment;
    
    if (!$cnt--) break;
}