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?

3
  • Have you tried anything to solve the problem yourself? Commented Jan 11, 2015 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. Commented Jan 11, 2015 at 20:10
  • Actually I think that the best approach as regards to performance is what @HenrikPetterson suggested. Check these benchmarks. Commented Jan 11, 2015 at 20:21

1 Answer 1

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]; 
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Can you please elaborate? You are using terms I am yet to learn :)
This is what I wrote in my comment to my question, but it doesn't seem like the best approach when considering performance...
Usually I would have a field with a status so I could check it instead of having a comment saying approved.
Is this the only and best approach when considering performance?
Well, if you controlled your source, you could make it not to send the comments that are not approved in first place so you don't need to check it.
|

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.