PHP Next in an Associative Array…

This might me useful for some people…

If you want to echo the value of the next ‘key->value pair’ in an associative array. You can use:

$keys = array_keys($arr);
echo $arr[$keys[(array_search($key, $keys)+1)]];

Where $arr is the associative array, $keys is the $arr keys as values with numerical keys and $key is the $arr key of the key->value pair prior to the one you want to output.

Explained:

$arr = array(
'12' => 'a',
'14' => 'b',
'20' => 'c',
'23' => 'd'
);

And you want to output the next value after ’14’=>’b’, which would be ‘c’. All you need to do is define $key = 14;

If you want to output the previous to ’14’=>’b’, just change the “+” to a “-“.

PHP Next in an Associative Array…

PHP Cleaning Arrays…

When arrays are built by user input. You can sometimes experience “blank” values within that array. Sometimes set to “0”, “FALSE” or “NULL”.

You can use array_filter to remove empty (NULL) elements:

$emptyRemoved = array_filter($linksArray);

If you have (int) 0 in your array, you may use the following:

$emptyRemoved = remove_empty($linksArray);

function remove_empty($array) {
 return array_filter($array, '_remove_empty_internal');
 }

function _remove_empty_internal($value) {
 return !empty($value) || $value === 0;
 }

Maybe your elements are not empty per say but contain one or more spaces… You can use the following before using array_filter

$trimmedArray = array_map('trim', $linksArray);

 

Sourced from: http://stackoverflow.com/questions/3654295/remove-empty-array-elements

PHP Cleaning Arrays…

ChangeLog Generator…

I’ve been looking into source control and version control software to help manage and organise some of our code. The majority of them don’t seem to fit our workflow and are to restrictive or complicated for tiny projects. I’m a massive fan of the good old ChangeLog (https://en.wikipedia.org/wiki/Changelog) which does not scale well with larger projects.

So, I’ve built a little “one page” script (technically a few files if you include images for the GUI). Nice and simple app to manage a ChangeLog for a larger project but not quite big enough for full version management software.

Continue reading “ChangeLog Generator…”

ChangeLog Generator…

PHP Strings and Characters

Here some simple tips to help with manipulating text, the simplest of things can be the most valuable. 🙂

First, if you only want to pull one character from a string, it’s a lot easier to use the following:

 $string = 'puppy';
 echo $string[0]; // p
 echo $string[1]; // u
 echo $string[2]; // p ...and so on

And here’s the basic concept behind the substr() function:

substr($string, start # [, length #])

– length is in brackets because it’s optional

Now let’s use this function to get a better idea of what it does.

 $string = 'categories';
 echo substr($string, 0); // 'categories' because we asked to start at the first character (which is 0 from the first example above) and goes right until end of string
 echo substr($string, 3); // 'egories' because started at the third character in the string and went to the end
 echo substr($string, -1); // 's' this is different from above because it starts at the end and goes left that number of characters
 echo substr($string, -3); // 'ies'

echo substr($string,0,-1); // 'categorie' strips last letter off
 echo substr($string,3,4); // 'egor' - starts at the fourth character (remember 0 is the first) and shows 4 characters total (length)
 echo substr($string,1,3); // 'ate' - starts at the second character and shows 3 characters total (length)
 echo substr($string,1,-2); // 'ategori' because we started at the second character and also stripped off the last two with the "-2"
 echo substr($string,-3,-2); // 'i' since we're starting from the third character from the left and then are stripping off two characters from that with the "-2"

I sometimes use this if I only want to display a preview description rather than showing the whole large description.

$text = 'Great for home, school or travel. Wonderful gift item!';
 echo substr($text,0,25).'...'; // displays "Great for home, school or..."
PHP Strings and Characters

PHP Add Key & Value to Beginning of an Array…

So it turns out there is no built in function to add a key and value to the start of an array. There is;

 

array_unshift() – Prepend one or more elements to the beginning of an array.

 

However, this will only add a value. So the method we use is to create a new array with the key and value you wish to add to another and use;

 

array_combine — Creates an array by using one array for keys and another for its values.

 

For example:

$existingArray = array("fred" => "orange", "john" => "IsaSpy");
$array['our_key'] = "our_value";

$newArray = array_combine($existingArray, $array);

print_r($newArray);

//boom
PHP Add Key & Value to Beginning of an Array…

Fend off the bad bots…

I have now discovered a few tips and tricks to fend off those bad bots, crawlers, harvesters, you name it – all at the application layer.

First of all you need to create yourself a simple blocklist of IP’s, one IP per line, IP’s you don’t want visiting your site. (hopefully ours will be published for public use soon)

123.567.678.9
657.387.93.2
1.1.1.14
etc

The PHP needs to be something simple like a script that checks if the users IP is in the text file and if it is, display a “No Entry Error”. Originally my script only displayed a HTML page with text along the lines of “Your IP address has been blocked from our network due to suspicious activity, you are being monitored. Continue reading “Fend off the bad bots…”

Fend off the bad bots…

Google Currency Conversion…

Well, the api is pretty straight forward.  It was found in the Currency Conversion gadget from iGoogle by http://oohhyeah.blogspot.com/2009/01/google-currency-conversion-api.html

Here is the example:
http://www.google.com/ig/calculator?hl=en&q=100EUR%3D%3FGBP

And the resposnse looks like this:
{lhs: “100 Euros”,rhs: “191.745037 British pounds”,display: “DISPLAY_FULL_PAGE”,error: “”,icc: true}

Heres how to do it in PHP


$amount = "100";

$from_Currency = "EUR";

$googleResponce = file_get_contents('http://www.google.com/ig/calculator?hl=en&q=' . $amount . $from_Currency . '%3D%3FGBP');

$googleResponce = explode(',', $googleResponce);

$numberInGBP = number_format(round(trim(str_ireplace(array('rhs: "', ' British pounds"'), '', $googleResponce[1])), 2), 2);

echo $numberInGBP;
Google Currency Conversion…

PHP Simple Calendar…

I have been looking for a proper, simple and well formed PHP calendar. I eventually found a promising looking script on emanueleferonato.com however it was not well formed (PHP or Output HTML)

I have tweaked the script to be correctly formed 😀 You can output any month of any year (within PHP restrictions) and you can start you week on any day of the week. i.e. Americans start on Saturday where as the English start on Monday.

Continue reading “PHP Simple Calendar…”

PHP Simple Calendar…

PHP Browser Detection…

Detecting the user’s browser type and version is helpful in web applications that harness some of the newer bleeding edge concepts. With the browser type and version you can notify users about challenges they may experience and suggest they upgrade before using such application. Not a great idea on a large scale public site; but on a private application this type of check can be helpful.

Searching for a way to do this at the PHP layer and not at the client layer was more of a challenge than I would have guessed; the only script available was written by Gary White and Gary no longer maintains this script because of reliability. I do agree 100% with Gary about the readability; however, there are realistic reasons to desire the user’s browser and browser version and if your visitor is not echoing a false user agent we can take an educated guess.

Check out the script and find out more information on the link below

http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php/

PHP Browser Detection…

PHP preg_match and Regular Expressions…

Regular expressions are a powerful tool for examining and modifying text. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely. However, you should note that because regular expressions are more powerful, they are also slower than the more basic string functions. You should only use regular expressions if you have a particular need.

This tutorial gives a brief overview of basic regular expression syntax and then considers the functions that PHP provides for working with regular expressions.

PHP supports two different types of regular expressions: POSIX-extended and Perl-Compatible Regular Expressions (PCRE). The PCRE functions are more powerful than the POSIX ones, and faster too, so we will concentrate on them.

Continue reading “PHP preg_match and Regular Expressions…”

PHP preg_match and Regular Expressions…