Lovelock
Lovelock

Reputation: 8085

PHP in_array not working with current array structure

I am using a custom method to return a query as an array.

This is being used to check if a discount code posted is in the DB.

The array ends up as example:

Array
(
[0] => stdClass Object
    (
        [code] => SS2015
    )

[1] => stdClass Object
    (
        [code] => SS2016
    )

)

So when I am trying to do:

if ( ! in_array($discount_code, $valid_codes)) {

}

Its not working. Is there a way I can still use the function for query to array I am using and check if its in the array?

No issues, I can make a plain array of the codes but just wanted to keep things consistent.

Upvotes: 1

Views: 338

Answers (4)

splash58
splash58

Reputation: 26153

why not solve it as a school task - fast and easy:

for($i = 0; $i < count($valid_codes); $i++) if ($valid_codes[$]->code == $discount_code) break;
if ( ! ($i < count($valid_codes))) {  // not in array
}

Upvotes: 0

num8er
num8er

Reputation: 19372

Read about json_encode (serialize data to json) and json_decode (return associative array from serialized json, if secondary param is true). Also array_column gets values by field name. so we have array of values in 1 dimensional array, then let's check with in_array.

function isInCodes($code, $codes) {
    $codes = json_encode($codes); // serialize array of objects to json
    $codes = json_decode($codes, true); // unserialize json to associative array
    $codes = array_column($codes, 'code'); // build 1 dimensional array of code fields
    return in_array($code, $codes); // check if exists
}

if(!isInCodes($discount_code, $valid_codes)) {
// do something
}

Upvotes: 1

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5445

try this

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
    if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
        return true;
    }
}

return false;
}

then

echo in_array_r("SS2015", $array) ? 'found' : 'not found';

Upvotes: 0

axiac
axiac

Reputation: 72266

Use array_filter() to identify the objects having property code equal with $discount_code:

$in_array = array_filter(
    $valid_codes,
    function ($item) use ($discount_code) {
        return $item->code == $discount_code;
    }
);

if (! count($in_array)) {
    // $discount_code is not in $valid_codes
}

If you need to do the same check many times, in different files, you can convert the above code snippet to a function:

function code_in_array($code, array $array)
{
    return count(
        array_filter(
            $array,
            function ($item) use ($code) {
                return $item->code == $code;
            }
        )
    ) != 0;
}


if (! code_in_array($discount_code, $valid_codes)) {
    // ...
}

Upvotes: 0

Related Questions