JavaScript Tricks; URLEncode, Foreach and Remove last character

I have come across some neat (if not mind blowing) tricks with JavaScript recently.

Firstly, I needed JavaScript code that copied PHP’s urlencode().
This function returns an encoded string where all non-alphanumeric characters except - _ . are replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

JavaScript has 2 functions to emulate urlencode(), but both fall short…
The escape function encodes all non-alphanumeric characters except * @ / + – _ .
The encodeURIComponent function encodes all non-alphanumeric characters except spaces and ! ‘ ( ) * ~

The winner for me though is encodeURIComponent as it encodes all UTF-8 characters while escape only encodes ISO Latin characters.

With this in hand, mozilla help provide a neat function.
Continue reading

Post XML with HTTPS Authentication using PHP and cURL

Recently I needed to post XML to a particular API and this API required HTTPS authentication. So I needed to send a username / password with the request.

This was pretty straightforward in C#.NET ( at least from my foggy memory ). You needed to use NetworkCredentials. But it was a bit difficult to find a similar way of doing this in PHP… but eventually I found this gem.

This uses cURL which is just a library to send and receive data from remote sites. Now all I needed was a neat way of using cURL to post XML… and I found a neat implementation here.

Two plus two and you get …
Continue reading

Odd or Even Number

I love gems like this. I come across them from time to time but they never stick… then I do a search to find them again.

Anyway a simple way to determine if a number is odd or even, use the following code.

function is_odd( $number ) {
    return $number & 1;
}

Quick explanation
& is a binary AND.

If you have a binary value, and you AND with another binary value, then the result will be the bitwise AND of the two.

Binary values are a series of bits or 1′s and 0′s. However we are only concerned with the rightmost one ( the least significant bit ) as when a binary value ends with a 1, it is odd… when it ends with a 0 it is even.

Now, if I pass that function say the number 13, the binary value will look like 1101.
When you AND with a 1, or binary value 0001, it looks like this…

1101 & 0001 = 0001

We look to the least significant bit, which is a 1, which means the number is odd.

A simple explanation of binary can be found here.