skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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,

    Login or Signup to reply.
  3. 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
            )
    
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search