up vote 0 down vote favorite
share [fb]

I have this array of objects. However I want to only pull out the object which meets a certain criteria. If you look at the "post_title" key, I want to only pull out the object if it does not contain a comma. Is this possible?

So in my example below, I want to pull out the array in index 2 as that is the only one that has no comma in the "post_title" key.

Array
(
    [0] => stdClass Object
        (
            [ID] => 504
            [post_title] => Playroom (Black, Custom 2)
        )

    [1] => stdClass Object
        (
            [ID] => 503
            [post_title] => Playroom (Black, Custom 1)

        )

    [2] => stdClass Object
        (
            [ID] => 252
            [post_title] => Play (Black)

        )

)
1

Thank you for looking at this.

link|improve this question

74% accept rate
feedback

4 Answers

up vote 0 down vote accepted

Yes you can but you will have to code it yourself, like this:

$results = array();
foreach ($source as $obj) {
  if (strpos($obj->post_title, ',') === false) {
    $results[] = $obj;
  }
}
// $results will now have the elements filtered
link|improve this answer
Thank you...I tried foreach loop but didn't think to rebuild a new array...thanks again. – Rick Dec 31 '11 at 19:01
Please note that the answers advocating array_filter() are generally accepted as a "better" way to do this. – rdlowrey Dec 31 '11 at 19:14
For PHP < 5.3 I would have to disagree: I've never liked to write full functions for things that I won't be using anywhere else, and it also becomes less readable if you are inside a method/function because you have to declare your callback somewhere else. – rabusmar Dec 31 '11 at 19:27
feedback

check array_filter function - http://php.net/manual/en/function.array-filter.php

$myArray = /*snip*/;

function titleDoesNotContainComma($object) {
    return strpos($object->post_title, ',') === false; 
}

$filteredArray = array_filter($myArray, 'titleDoesNotContainComma');
link|improve this answer
feedback

What have you tried? You could just foreach over the array and build a new array with the relevant results. Alternatively you could use array_filter, something like this:

function hasComma( $object ) {
  if( strpos( $object->post_title, ',' ) ) {
    return false;
  } else {
    return true;
  }
}

var_dump( array_filter( $array, 'hasComma' ) );
link|improve this answer
feedback

Use a closure if you have PHP5.3+ with array_filter() ... otherwise define a function like @sakfa specifies.

$filtered = array_filter($arr, function($x) { return strstr($x->post_title, ','); });
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.