-1

I want to search something in my SESSION. I think its an array. When I am printing the $_SESSION["basket"], the output will be:

[
    ["6"],
    ["5"],
    ["8"]
]

These numbers are product ids. I wanna search id on this output. How can I do this?

For ex: I wanna search 8 in [["6"],["5"],["8"]], then output will be true.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58

2 Answers2

1

The reason why your in_array is not working is because your values 6, 5 and 8 are stored inside another array in your main array.

So to search for a value, you could loop through each array with a function:

Non-recursive (1 level depth search)

function searchInArray($array, $value){
    // If the array parameter is not an array and the value parameter is an array, return false
    if(!is_array($array) || is_array($value))
        return false;

    // If the value is found in the main array, return true
    if(in_array($value, $array))
        return true;

    // Loop through each subarray
    foreach($array as $subarray){
        if(in_array($value, $subarray))
            return true;
    }        
}

Let's say this is your array:

$array = [[6], [5], [8]];

And if we var_dump with var_dump(searchInArray($array, 8)); the result:

bool(true)

Recursive (infinite depth search)

With this function, it will search inside each subarray... which is a recursive function:

function recursiveSearch($array, $value){
    // If the array parameter is not an array and the value parameter is an array, return false
    if(!is_array($array) || is_array($value))
        return false;

    // If the value is found in the main array, return true
    if(in_array($value, $array))
        return true;

    // Loop through each subarray and make a recursive call
    foreach($array as $subarray){
        if(recursiveSearch($subarray, $value))
            return true;
    }

    return false;
}

So let's suppose this time this is your array:

$array = [[6], [5], [8, [9]]];

The result:

var_dump(recursiveSearch($array, 4)); // false
var_dump(recursiveSearch($array, 8)); // true
var_dump(recursiveSearch($array, 9)); // true
Community
  • 1
  • 1
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
0

The solution can be much simpler because your id values all exist in a single column of the multidimensional array. Use array_column() to generate a 1-dimensional array from the first column of values, then call in_array() on the array.

Code: (Demo: https://3v4l.org/UN6PZ )

$_SESSION['basket']=[["6"],["5"],["8"]];
var_export(in_array('8',array_column($_SESSION['basket'],0)));

Output:

true
mickmackusa
  • 43,625
  • 12
  • 83
  • 136