Skip to content
Advertisement

What exactly the unset() function is doing here?

This code takes a number like 2017 and returns the NEXT highest (not total highest, like 7021) number, so in this case 2071

I understand every bit of except the if (($key = array_search($currentNumber, $tmpArray, true)) !== false) { unset($tmpArray[$key]); — what exactly is happening here? Please help and I will accept immediately 🙂

I get that $key is either true or false if the current number is found in the tmpArray variable, but why is it set to !== false? Instead of === true? And what does unsetting do in this case?

JavaScript

Advertisement

Answer

The function takes the input (2017), and first finds the largest number than can be made with those digits, by ordering them in descending order (7210).

It then loops over every number between those two bounds*, and for each digit in that number, it sees if that digit is “available” in the input. Annotated below:

JavaScript

* As an aside, this is probably not the most efficient way of performing this task

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement