Skip to content
Advertisement

Check if value exists with array_search()

I have an array called $resultstatsmatch with the folowing output:

  Array
    (
        [40] => Array
            (
                [stat1] => 20
                [bonusidbonusstat0] => 40
            )
    )

Now I want to check if the array key [bonusidbonusstat0] contains the value “40”. If yes, it should appear a text.

Therefore I´m using the array_search() method but for some reason it doesn´t work, the text is shown, no matter the value exists or not.

This is the code:

$bonusStat2 = "40";
$columnname2 = "bonusidbonusstat0";
$res = array_search($bonusStat2, array_column($resultstatsmatch, $columnname2));

if($res == ''){
    echo 'exists';
} else {
    echo 'notExists';
}

Advertisement

Answer

Instead of using the array_search, I would recommend to use in_array() to check if bonusStat2 exist in the result of array_column

<?php

$array = [];
$array[40] = [];
$array[40]['stat1'] = 20;
$array[40]['bonusidbonusstat0'] = 40;

$res = array_column($array, 'bonusidbonusstat0');
$res = in_array('40', $res);

if ($res) {
    echo 'exists';
} else {
    echo 'notExists';
}

Try it online!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement