I have a function called insert which takes two parameters (name and telnumber).
When I call this function I want to add to an associative array.
So for example, when I do the following:
insert("John", "999");
insert("Adam", "5433");
I want to it so be stored like this:
[0]
{
name: John, number: 999
}
[1]
{
name: Adam, number: 5433
}
Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.
JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.
Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. This method accepts an unlimited number of arguments, and you can add as many elements as you want at the end of the array.
An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.
Something like this should do the trick:
var arr = [];
function insert(name, number) {
arr.push({
name: name,
number: number
});
}
I would use something like this;
var contacts = [];
var addContact = function(name, phone) {
contacts.push({ name: name, phone: phone });
};
// Usage
addContact('John', '999');
addContact('Adam', '5433');
I don’t think you should try to parse the phone number as an integer as it could contain white-spaces, plus signs (+) and maybe even start with a zero (0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With