-1

I have this array:

array [▼
      0 => array:5 [▼
        "id" => 1
        "user_id" => 15
        "parent_campaign_id" => 69464
        "child_campaign_id" => 69464
        "cpm" => "1.00"
      ]
      1 => array:5 [▼
        "id" => 2
        "user_id" => 15
        "parent_campaign_id" => 69464
        "child_campaign_id" => 396331
        "cpm" => "2.00"
      ]
      2 => array:5 [▼
        "id" => 3
        "user_id" => 15
        "parent_campaign_id" => 69464
        "child_campaign_id" => 398032
        "cpm" => "3.00"
      ]
    ]

How can I know if a number 396331 exists in that array and the key should be child_campaign_id.

I tried in_array() but it seems it is not working correctly since the keys of this array is different.

TylerH
  • 20,799
  • 66
  • 75
  • 101
PinoyStackOverflower
  • 5,214
  • 18
  • 63
  • 126
  • 4
    Possible duplicate of [PHP: Check if value and key exist in multidimensional array](http://stackoverflow.com/questions/6990855/php-check-if-value-and-key-exist-in-multidimensional-array) – Rajdeep Paul Dec 01 '16 at 14:23

2 Answers2

8

The simple and clean version uses array_filter.

$filtered = array_filter($original, function($element) {
    return $element['child_campaign_id'] === 396331;
});

if (count($filtered)) {
    // it exists
} else {
    // it doesn't
}

It is, of course, possible to use a variable as the search key if you wish:

$search = 396331; // or whatever
$filtered = array_filter($original, function($element) use ($search) {
    return $element['child_campaign_id'] === $search;
});

Note that the downside of this is that it searches through the entire array, reduces it and then checks to see if there is anything left. A more efficient way, if you have a very large array, would be to loop through and break; when you reach the first matching array element.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
3

Try this, it will print array index, it will give false result if value is not exist.

$index_array= array_search(396331, array_column($array, "child_campaign_id"));
var_dump($index_array);

DEMO

Dave
  • 3,073
  • 7
  • 20
  • 33
  • Note that you can also play with the third parameter of `array_column`, this way you don't have to search the array: `isset(array_column($arr, 'id', 'child_campaign_id')[398032])` (or using `key_exists`) – Casimir et Hippolyte Dec 01 '16 at 15:48