Moving array element to top in PHP

Here is a solution which works correctly both with numeric and string keys: function move_to_top(&$array, $key) { $temp = array($key => $array[$key]); unset($array[$key]); $array = $temp + $array; } It works because arrays in PHP are ordered maps. Btw, to move an item to bottom use: function move_to_bottom(&$array, $key) { $value = $array[$key]; unset($array[$key]); $array[$key] … Read more

Adding Event Listeners on Elements – Javascript

The way you are doing it is fine, but your event listener for the click event should be like this: button.addEventListener(“click”, function() { alert(“alert”);}); Notice, the click event should be attached with “click”, not “onclick”. You can also try doing this the old way: function onload() { var button = document.getElementById(“buttonid”); // add onclick event … Read more

How to count identical string elements in a Ruby array

Ruby v2.7+ (latest) As of ruby v2.7.0 (released December 2019), the core language now includes Enumerable#tally – a new method, designed specifically for this problem: names = [“Jason”, “Jason”, “Teresa”, “Judah”, “Michelle”, “Judah”, “Judah”, “Allison”] names.tally #=> {“Jason”=>2, “Teresa”=>1, “Judah”=>3, “Michelle”=>1, “Allison”=>1} Ruby v2.4+ (currently supported, but older) The following code was not possible in … Read more

How can I loop through enum values for display in radio buttons? [duplicate]

Two options: for (let item in MotifIntervention) { if (isNaN(Number(item))) { console.log(item); } } Or Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key]))); (code in playground) Edit String enums look different than regular ones, for example: enum MyEnum { A = “a”, B = “b”, C = “c” } Compiles into: var MyEnum; (function (MyEnum) { MyEnum[“A”] = “a”; MyEnum[“B”] … Read more

Can I use document.getElementById() with multiple ids?

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options: You could implement your own function that takes multiple ids and returns multiple elements. You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string . … Read more