How to add/remove an element to/from javascript array at/from the given position?

In previous week we have a requirement to add an element to javascript array at the given position.

To fulfill our requirement we have used javascript splice method.

The splice() method is changing the original array and add/remove an element to/from the given position.

It is returning the removed element. And it has three arguments.

Where first argument is “index”, which is an integer to specify at which position add/remove element.

Second argument is “how many”, which is the number of elements to be removed. If this argument is set to 0 then no element will be removed.

And third argument is “element”, which is the new element(s) will be added to the array and this argument is optional.

Now follow the under given example, which adds/removes an element to/from javascript array at/from the given position.

var vehicles = ["bicycle", "car", "bus"];
vehicles.splice(2,0,"truck");
document.write("Added: " +  vehicles + "<br />");
document.write("Removed: " + vehicles.splice(1,2,"tractor,train") + "<br />");
document.write("Vehicles: " + vehicles);

How to make an array from string using php?

Just a week before we have got a requirement, to make an array from string using php.

To satisfy our requirement we have used php explode function.

The explode() is breaking a string into an array, and returns an array of strings.

It has three arguments which are separator, string and limit.

Where first and second arguments are mandatory and third is optional.

First argument is separator, which describes where to break the string.

Second argument is string to break.

And the third argument is limit, which describes the maximum number of elements an array will contain.

Follow the under given example, which makes an array after breaking a string.

$string = "Hello World! This will make an array from string.";
echo "<pre>";
print_r(explode(" ", $string));
print_r(explode(" ", $string, 2));
print_r(explode(" ", $string, -2));
print_r(explode(" ", $string, 0));
echo "</pre>";

How to check variable / object is set or not in javascript?

Before few days we have a requirement to check that, the variable which we want to use is already set and defined or not.

To fulfill our requirement we have used javascript typeof operator.

The typeof operator in javascript returns the data type of given argument, such as whether an argument is numeric, string, boolean, object, null or undefined.

Here if we pass any variable / object as an argument which has not defined, then it returns undefined.

Following the example to check variable / object is set or not and its data type.

var check_numeric = 10;

alert(typeof(check_numeric));

alert(typeof("Hello"));

alert(typeof(true));

alert(typeof(check_undefined));