php sort multi dimensional array by value

This post explains how to php sort multi dimensional array by value.

$books = array(
array(“type”=>”maths”, “price”=>13.50),
array(“type”=>”science”, “price”=>21.99),
array(“type”=>”social”, “price”=>15.75),
);

$books = sortMultiArrayByValue($inventory, ‘price’,’desc’);
echo “<pre>”;
print_r($books );

function sortMultiArrayByValue($array, $value, $sort_order = ‘asc’){
$sortarray = array();
if(is_array($array)){
foreach ($array as $key => $row){
$sortarray[$key] = $row[$value];
}
if(strtolower(trim($sort_order)) == ‘asc’){
array_multisort($sortarray, SORT_ASC, $array);
}else{
array_multisort($sortarray, SORT_DESC, $array);
}
}
return $array;
}

 

Output:

Array
(
[0] => Array
(
[type] => science
[price] => 21.99
)

[1] => Array
(
[type] => social
[price] => 15.75
)

[2] => Array
(
[type] => maths
[price] => 13.5
)

)

 

Using Memcache for php

Using Memcache for PHP

This article will explain the process of using memcache for php dynamic websites. Memcache is used to implement cache mechanism using PHP. There are also many cache engines available for PHP, but using memcache for PHP will provide some additional benefits.

Memcache itself providing procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

Below are the requirements that has to be accomplished before going to explain the process of using memcache for PHP.

1) Memcache service has to be installed and started. For windows operation system read this page and for Ubuntu read this page

2) Memcache php extension is installed and enabled to run with PHP. To know installation process read this page.

Considering both Memcache service and Memcache php extension are started and working fine, here we go with Using Memcache for PHP explanation.

Here’s some sample code from php.net site

<?php
  $memcache = new Memcache;
  $memcache->connect("localhost",11211); # You might need to set "localhost" to "127.0.0.1"
  echo "Server's version: " . $memcache->getVersion() . "<br />\n";
  $tmp_object = new stdClass;
  $tmp_object->str_attr = "test";
  $tmp_object->int_attr = 123;
  $memcache->set("key",$tmp_object,false,10);
  echo "Store data in the cache (data will expire in 10 seconds)<br />\n";
  echo "Data from the cache:<br />\n";
  var_dump($memcache->get("key"));

?>

If you have any errors, it will most likely be because the php extension didn’t run. Check the webserver error log to see if it had problems starting. The most common problem is the version of memcache.dll is not compatible with the version of php you are running.

Installing Memcache PHP Extension

Installing Memcache PHP Extension

Installing Memcache PHP extension article will explain how to install Memcache dll file both in Xampp and Wamp servers.

Follow the below steps for Installing Memcache PHP Extension in Wamp or Xampp

1) Download the memcache php extension zip file form this link

2) Unzip and find the php_memcache.dll file.

3) For Xampp server place the dll file in D:\xampp\php\ext folder. Here considering that Xampp is installed in D Drive.

4) For Wamp server place the dll file in D:\wamp\bin\php\php5.2.9-1\ext folder. Here considering that Wamp is installed in D Drive.

5) Open the php.ini file which is located at D:\xampp\php  or D:\wamp\bin\php\php5.2.9-1\  for Xampp or Wamp servers respectively

6) Find and replace

;extension=php_memcache.dll

with

extension=php_memcache.dll

7) If you cannot find this line simply add the following to the extensions list

extension=php_memcache.dll

8) Restart the server ( Wamp/Xampp)

To check the Installation is success or not

  • Please create a php file (phpinfo.php) some where in the wamp/xampp.
  • Run that file through browser.
  • Search for Memcache in the page .
  • If you can see it, means the installation is success and is working fine.

Note : If you have any errors, it will most likely be because the php extension didn’t run. Check the webserver error log to see if it had problems starting. The most common problem is the version of memcache.dll is not compatible with the version of php you are running.

Read Installation of Memcached service on Windows here

Read Installation of Memcached service on Ubuntu here

php group numbers into intervals

php group numbers into intervals

The article php group numbers into intervals will explain how to group the provided numbers in to intervals.

 

function group_nums($array) {
  $ret = array();
  $temp = array();
  foreach($array as $val) {
    if(next($array) == ($val + 1))
      $temp[] = $val;
    else
      if(count($temp) > 0) {
        $temp[] = $val;
        $ret[] = $temp[0].’:’.end($temp);
        $temp = array();
      }
      else
        $ret[] = $val;
    }
  return $ret;
}

$nums = array(1, 2, 3, 4, 14, 21, 23, 28, 29);
print_r(group_nums($nums));

// OUTPUT 
Array
(
    [0] => 1-4
    [1] => 14
    [2] => 21
    [3] => 23
    [4] => 28-29
)

 

Compare Joomla and Drupal Terminology

Compare Joomla and Drupal Terminology

Joomla and Drupal are the two most popular and most used content management systems (CMS) in web. Both these CMS are open source ( free to use)  and built on PHP + MySQL. Both these CMS vary significantly in terms of features, capability, flexibility and terminology. Below, is the list to compare Joomla and Drupal Terminology.

Joomla : 

Joomla is an award-winning, open-source CMS (content management system) with over 35 million downloads worldwide and still counting. It has thousands of extensions and designs and is backed by a large community of coders, developers and support staff. Joomla is very versatile, user-friendly and mobile-ready, making it a very sought-after CMS for corporate websites.

Drupal : 

Drupal is open source software maintained and developed by a community of 630,000+ users and developers. Drupal is used to build everything from personal blogs to enterprise applications. Thousands of add-on modules and designs let you build online communities, media portal, online store, and more!

 Joomla and Drupal Terminology

  1. Joomla Template is called Theme in Drupal.
  2. Component = Module.
  3. Module = Block.
  4. Mambot/Plugin = Input filter.
  5. Menu-Horizontal = Primary Links
  6. Menu-Vertical = Navigation
  7. Dynamic Content Item = Story
  8. Static Content = Page
  9. Back-end = there is no back-end in Drupal,
  10. SEF = Clean URLs (but some docs refer to SEF, too).
  11. Section = Taxonomy Vocabulary/Term
  12. Section Title = Taxonomy Term (master)
  13. Category = Taxonomy Term (child)
  14. Introtext = Teaser
  15. Maintext = Body (see explanation below)
  16. Pathway = Breadcrumb

Other terms are the same, such as: forum discussion, editor, search, region, comment, subject/title, preview, html tag, view, edit, advertising/banner, log in/log out, profile, avatar, access control, logs, cache, site maintenance, RSS feed, parent-child and snippets.

Read more about Drupal here

Read more about Joomla here

PHP remove non alphanumeric characters from string

In many cases there will be a requirement to remove non alphanumeric characters from string.
The cases can be filtering the user input data, displaying only alphanumeric content, filtering the data for inserting in to database etc.

If the requirement is to allow only alphanumeric characters from the user input and remove non alphanumeric characters from string, the below function is the right way to move on.

 

function onlyAlphanumeric($string) {
		if (!is_array($string)) {
			return preg_replace("/[^a-zA-Z0-9]/", '', $string);
		}
// in string is array
		$cleaned_string = array();
		foreach ($string as $key => $value) {
			$cleaned_string[$key] = preg_replace("/[^a-zA-Z0-9]/", '', $value);
		}

		return $cleaned_string;
	}

This onlyAlphanumeric function not only remove non alphanumeric characters form string but also removes from array.

By modifying the function we can allow an array of additional characters that are not to be removed from the string or array.

 

function onlyAlphanumeric($string, $allowed_characters = array()) {
		$allow = '';
		if (!empty($allowed_characters)) {
			foreach ($allowed_characters as $character) {
				$allow .= "\\$character";
			}
		}

		if (!is_array($string)) {
			return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
		}
// if string is array
		$cleaned_string = array();
		foreach ($string as $key => $value) {
			$cleaned_string[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $value);
		}

		return $cleaned_string;
	}

$allowed_characters in the above function should be an array.

Example:

$allowed_characters = array(‘!’, ‘ ‘);

$string = “Hello @#$% World!”;

echo  onlyAlphanumeric($string,$allowed_character);

// output Hello  World!

 

PHP generate permalink through php and javascript

This Article explains how to generate permalink through php and javascript code.

 

Using Javascript:

<script type="text/javascript">
    function string_to_permalink(str) {
        str = str.replace(/^\s+|\s+$/g, ''); // trim
        str = str.toLowerCase();
        // remove accents, swap ñ for n, etc
        var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
        var to   = "aaaaeeeeiiiioooouuuunc------";
        for (var i=0, l=from.length ; i<l ; i++) {
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }
        str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
          .replace(/\s+/g, '-') // collapse whitespace and replace by -
          .replace(/-+/g, '-'); // collapse dashes
        return str;
    }
</script>

 

Using PHP :

function generate_permalink($string)
{
	if($string !== mb_convert_encoding( mb_convert_encoding($string, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
		$string = mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string));
	$string = htmlentities($string, ENT_NOQUOTES, 'UTF-8');
	$string = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\\1', $string);
	$string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
	$string = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $string);
	$string = strtolower( trim($string, '-') );
	return $string;
}

 

 

HTML open select box with a button click

Here is the simple Javascript code to open select box with a button click.

This javascript code also works for toggling the select box.

<script type="text/javascript">
    function expandSelect(id){
    var select_flag = document.getElementById('select_flag').value;
        if(select_flag==1){
            var select_box = document.getElementById(id);
            select_box.size = 1;
            document.getElementById('select_flag').value = 0;
        }else{
            var select_box = document.getElementById(id);
            select_box.size = select_box.options.length; 
            document.getElementById('select_flag').value = 1;
        }
   }
</script>

<button onclick="expandSelect('select_box')"> Toggle Select Box </button>

<div id="container">
    <select name="select_box" id="select_box" >
        <option value="">Select</option>
        <option value="">option1</option>
        <option value="">option2</option>
        <option value="">option3</option>
        <option value="">option4</option>
        <option value="">option5</option>
        <option value="">option6</option>
    </select>
    <input type="hidden" name="select_flag" id="select_flag" value="0">
</div>

 

Optimising PHP code

This article helps you to improve the performance of your PHP scripts, by optimising php code.  You can apply these few best practices to speed up your script.

PHP engine have made a number of significant performance improvements over the years.  If you are using old versions of PHP such as PHP4 or below, you might have to consider upgrading to the latest version of PHP.

 

  • Use static methods when possible as they are much faster by a factor of 4.
  • Echo is faster than print
  • Unset your variables after usage to free up the memory
  • Close database connections when you’re done with them
  • Don’t call the function as part of the loop condition

Consider this example:

for ($i = 1; $i < count($myarr); ++$i) {

//

}

A much better solution is to calculate the array size just once, outside of the loop, like this:

$len = count($myarr);

for ($i = 1; $i < $len; ++$i) {

//

}

 

  • Methods in derived classes run faster than ones defined in the base class
  • Use predefined functions of PHP as much as possible
  • Use single quotes rather than double quotes to produce strings without the use of variables to make things little fatser, as PHP will parse the string with double quotes.
  • Do NOT use SQL wildcard select. eg. SELECT *
  • Try to index the fields that are commonly used in your SQL WHERE statements.

 

  • Avoid using SQL queries within a loop

Consider this example:

foreach ($userList as $user) {

$query = ‘INSERT INTO users (first_name,last_name) VALUES(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;

mysql_query($query);

}

Instead of using a loop, you can combine the data into a single database query.

$userData = array();
foreach ($userList as $user) {
$userData[] = ‘(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;
}
$query = ‘INSERT INTO users (first_name,last_name) VALUES’ . implode(‘,’, $userData);
mysql_query($query);

  •  str_replace() is much more efficient than regular expressions like ereg_replace() and preg_replace() at replacing strings.
  • If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace()
  • Consider using a  ternary operator, instead of using an if/else statement altogether. The ternary operator frees up line space and makes your code less cluttered, making it easier to scan 
  • Using Suppression Operator @ is rather slow
  • Use Pre-increment where possible, as pre-increment (++$i) is much faster than post-increment ($i++)
  • enable output buffering, and to use gzip compression for the buffers.

To enable output buffering for all your scripts, open up your php.ini file and set output_buffering to 1 and output_handler to “ob_gzhandler” (without the quotes).

  • Use the array and string functions where possible. They are faster than writing equivalent code in PHP.
  • Use HTML caching if you have data that rarely changes. Even if the data changes every minute, caching can help provided the data is synchronized with the cache. Depending on your code complexity, it can improve your performance by a factor of 10.
  • Optimize your loops first. Move loop invariants (constants) outside the loop.
  • PHP script is slower than HTML page, so try to use HTML pages when possible
  • For searching for substrings, the fastest code is using strpos(), followed by preg_match() and lastly ereg().

php trim array values

This article we will explain how to trim array values using different ways in PHP .

Consider the example

$array = array('one', 
               ' two', 
               ' three ', 
               '       four', 
               'five            ',
               '      six         '
              );

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(4) " two"
  [2]=>
  string(7) " three "
  [3]=>
  string(11) "       four"
  [4]=>
  string(16) "five            "
  [5]=>
  string(18) "      six         "
}

We can trim the above declared array values in below mentioned three ways.

1)Trim array values using array_map and trim functions

$trimmed_array=array_map('trim',$array );
var_dump($trimmed_array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}

2) Trim array values using foreach

foreach($array as $key => $value)
{
	$array[$key] = trim($value);
}

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}

3) Trim array values using array_walk

function array_trim(&$value) 
{ 
    $value = trim($value); 
}

array_walk($array, 'array_trim');

var_dump($array);

array(6) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  string(4) "four"
  [4]=>
  string(4) "five"
  [5]=>
  string(3) "six"
}