1

Why this function does not work? After calling it, the same array is printed.

$myArray1 = ["Barcelona",  "Romania", "Cile", "France"];

function del(&$array, $item_to_del){
    foreach ($array as $item) {
        if ($item == $item_to_del){
            unset($item);

        }
    }
}

del($myArray1, "Barcelona");
var_dump($myArray1);
1
  • Because you're not actually deleting the item in the array. You're unsetting $item. Commented May 11, 2016 at 13:25

2 Answers 2

1

Just replace your del function with this. try this:

function del(&$array, $item_to_del){
    if (($key = array_search($item_to_del, $array)) !== false) {
        unset($array[$key]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

What will happen if the item repeats multiple time into the array ?
0

You must delete the index also.

Try this:

<?php

$myArray1 = ["Barcelona",  "Romania", "Cile", "France"];

function del(&$array, $item_to_del){
    foreach ($array as $key => $item) {
        if ($item == $item_to_del){
            unset($array[$key]);

        }
    }
}

del($myArray1, "Barcelona");
var_dump($myArray1);

1 Comment

Md Mahfuzur Rahman, thank you, that works, cool. But it is weird since it is not a map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.