Home > Software design >  check if value exists in multidimensional array and find index
check if value exists in multidimensional array and find index

Time:11-15

I have an multidimensional array like this:

$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"],
  "downloads2" => ["downloadnaam" => "eyetyy"],
];

I need to check if the value eyetyy exists in this array under the key downloadnaam
Then I need to find the index of this value and remove it from the array.

The expected result:

$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"]
];

I tried this:

$index = array_search($download->name, array_column($downloadArray, 'downloadnaam'));
if ($index !== null)
{
   unset($downloadArray[$index]);
   die("found index: " . $index);
}

$download->name contains 'eyetyy'
$downloadArray is my array
But it always dies and doesn't show any index on screen.
Can anyone help me?

CodePudding user response:

Try in this way:

$downloadArray = [
    "downloads1" => ["downloadnaam" => "fdgssgsfg"],
    "downloads2" => ["downloadnaam" => "eyetyy"],
];

$filter = "eyetyy";

// Search for index
$index = array_search($filter, array_column($downloadArray, "downloadnaam"));

if ($index !== false) {
    // Delete
    array_splice($downloadArray, $index, 1);
}

print_r($downloadArray);
die();

Output:

Array
(
    [downloads1]    Array
        (
            [downloadnaam]    fdgssgsfg
        )

)

CodePudding user response:

you can try this :

$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"],
  "downloads2" => ["downloadnaam" => "eyetyy"],
];

foreach ($downloadArray as $subKey => $subArray) {
            if (\in_array($subArray['downloadnaam'], ['eyetyy'], true)) {
              unset($downloadArray[$subKey]);
            }
        }

var_dump($downloadArray);

Regards,

CodePudding user response:

I got it working using this code

$downloadArray = array_filter($downloadArray, function ($item) use ($download) {
    return $item['downloadnaam'] != $download->name;
});

This way I don't need to find the index first.

Credits to @Cositanto

  • Related