0

I have a multidimensional array stored in $t_comments that looks something like this:

Array (
    [0] => Array
        (
            [0] => 889
            [1] => First comment
            [2] => 8128912812
            [3] => approved
        )

    [1] => Array
        (
            [0] => 201
            [1] => This is the second comment
            [2] => 333333
            [3] => deleted
        )

    // There is more...
)

Currently, I loop through the array like this:

foreach($t_comments as $t_comment) {
    echo $t_comment[0]; // id
    echo $t_comment[1]; // comment
    echo $t_comment[2]; // timestamp
    echo $t_comment[3]; // status
}

I want to foreach loop through the array and only display arrays that have the value approved (as seen above). How do I do this when having performance in consideration?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • Have you tried anything to solve the problem yourself? – Rizier123 Jan 11 '15 at 20:09
  • 1
    The closest I could think of was to do an if statement checking each loop if the status is 'approved', but that seems like a bad approach when considering performance. – Henrik Petterson Jan 11 '15 at 20:10
  • Actually I think that the best approach as regards to performance is what @HenrikPetterson suggested. Check these [benchmarks](http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function). – Masiorama Jan 11 '15 at 20:21

1 Answers1

1

The best possible solution is to not have to check in the first place.

If you controlled the source that inflate the $t_comment array you could make it not send the comments that are not approved.

For example, if you have something like:

$t_comments = get_comments

You could use something like:

$t_comments = get_approved_comments

But if you can't then you will have to iterate through each array looking for what you want.

To do so you have to put an "if" inside your foreach to check your variable content so you know it's approved and then you know you can show it, echoing it.

Example:

foreach($t_comments as $t_comment) {
    if($t_comment[3]=="approved"){
          echo $t_comment[0];
          echo $t_comment[1];
          echo $t_comment[2];
          echo $t_comment[3]; 
    }
}