Skip to content Skip to sidebar Skip to footer

Check If Value Exists In Multidimensional Array

I want to make my category menu responsive to the projects displayed. The projects have multiple categories so multiple category-menu-links can be active. Whichever category the pr

Solution 1:

You can use array_search() to search for a specific value in your array. This function returns the key corresponding to the value if found, false otherwise.

So what you will want to do is loop each subarray:

$category = $_GET['cat'];
$allProjects = array(
    'project1' => array('corporate'),
    'project2' => array('corporate', 'print'),
    'project3' => array('web')
);

foreach ($allProjects as $projectName => $categories) {
    $categoryIndex = array_search($category, $categories);
    if ($categoryIndex !== false) {
        echo 'active: ' . $categoryIndex;
        // Do something with $categoryIndex and $projectName here
    }
}

Update:

Looks like this is your answer:

$project = $_GET('project');
$category = $_GET('cat');

if (isset($allProjects[$project]) && in_array($category, $allProjects[$project])) {
    echo 'yes';
}

Solution 2:

I'm not sure, what is in $_GET['project'] in your condition, but this will at least make your code better readable. :)

isActive = false;
foreach($allProjects as $project) {
  if(in_array($_GET['cat'], $project) isActive = true;
}

Solution 3:

You perhaps want to go through the array using a foreach and set your active / non active indicator accordingly.


Post a Comment for "Check If Value Exists In Multidimensional Array"