Pages

Tuesday, 25 June 2013

Debate – .NET V. PHP: Top 10 .NET Myths Exposed

Debate – .NET V. PHP: Top 10 .NET Myths Exposed


Welcome to another SitePoint Debate. Today, daggers are drawn over that long-running battle of the technological titans — Open Source and Microsoft.
Specifically, we ask "Does .NET mean the end for PHP?" Judge for yourself…
Here’s a lesson for anyone in advertising – confuse your customers. It’s a dream ticket, as Microsoft have demonstrated with their marketing of .NET. You can almost hear Google straining under the weight of "What is .NET?" queries. It’s almost as cunning as PHP’s definition:
Q: What does PHP stand for?
A: Hypertext Preprocessor
Q: ?!?

As anyone browsing the SitePoint Forums knows, the hottest debate right now is PHP vs. Microsofts .NET. Discussions range from reasoned interchange to wild argument; anything from ".NET — who cares?" to ".NET — the greatest thing since sliced bread". What is clear from many posts is there’s a lot of uncertainty about what .NET actually is, and what impact it has on Web development.

This article is intended as "self-defence" for any PHP developers being harassed by over-exuberant .NET fanatics. It’s just one PHP’s coder’s point of view, but it should help clear up some of the most common misunderstanding, based on what’s been said at the SitePoint Forums in recent weeks.
The Top 10 Misconceptions
1. PHP is like an open source .NET.
You can’t compare PHP with .NET. .NET is an application framework (an environment for building and executing applications) not a programming language; it’s like comparing a truck to a road. PHP can, however, be compared to languages which run under .NET, such as ASP+ or C# (referred to as "Language.NET" here).
2. .NET is going to be the future of the Internet!
.NET is the future platform for all Microsoft technology — it’s not aimed solely at the Internet. In fact, it’s likely to make its first big appearance on corporate Intranets, with Office.NET and .NET versions of existing Windows NT server software.
3. .NET is the best technology for building a Website.
Both PHP and "Language.NET" are viable solutions for Web building. Whether it’s delivering a dynamic Web page generated from a database, sending an email, or interfacing with a payment gateway, both are perfectly capable. In assessing them as technologies for building your site, the only significant difference is the price. Try asking yourself "So how much does it cost to host this ASP.NET page I just wrote?"
4. PHP is not compiled, other than when it’s interpreted at runtime, whereas .NET enjoys all the benefits of being compiled.
Here’s news for the .NET crowd — you’ve finally caught up! Microsoft’s use of the word "compiled" in regard to .NET is not what a C++ coder would call "compiled". Zend, the corporate face of the PHP project, have been doing this for a while now with PHP Accelerator (for a free equivalent, try php-accelerator.co.uk). Unfortunately for Zend, they chose to describe what Accelerator does as "advanced caching" (read more on what Zend means by "caching"). For more technical detail, try this thread at SitePoint Forums.
5. ASP.NET has accountable support. PHP has none.
Apart from the support services offered by Zend (effectively PHP’s creators), NuSphere, ThinkPHP and other corporations also provide support for PHP. You don’t need it, thanks to the ever-expanding PHP community being what it is, but if your boss wants someone credible to blame, there’s more than enough choice!
6. .NET supports multiple languages. PHP doesn’t.
Try Java for PHP or the upcoming Python extension. Obviously this isn’t quite the same as C# or J# but the point needs to be made — PHP is very flexible, and offers useful solutions for the Internet. Don’t expect to find yourself to be writing a successful Website in Cobol.NET — it’s likely each .NET language will eventually "tune in" to a particular type of application development.
7. Language.NET has superior object orientation.
For those who know PHP and its limitations, you may be amused by this .NET FAQ — sound familiar? In fact with PHP 4.3 in the wings, it may be that PHP can claim superior OO support, when you consider that FAQ.
What is significantly different is "Language.NET" will force you into an object oriented approach from the start, while PHP won’t. The Web typically does not require OO — for your average dynamic Website, a few "hacked" scripts are perfectly fine if they meets the site’s requirements. Deliver a live site now, rather than a beautifully abstract piece of code that’s ready one year after it’s needed. Paraphrasing SitePoint’s recent interview with Rasmus Lerdorf, PHP’s down-to-earth approach to problem solving is what has made it a success. And when you need OO, it’s there waiting for you.
8. .NET offers superior templating and web development features.
Microsoft has come up with some nice features with .NET that are certainly enticing, like the datagrid, and the templating mechanism. But you could easily reproduce these with a little PHP (try DaDaBIK, for example).
The basic notion of templating is to separate logic from content, so those with artistic skills can make a site that looks good, while developers apply the code "behind the scenes". How Web designers feel about working with .NET’s templating system remains to be seen. With PHP, rather than being forced into a single approach, you have the choice of numerous Open Source projects (Smarty, Pat Template, etc.).
9. But corporations don’t like PHP.
Well apart from CBS, PHP is used on the corporate sites of Japan’s NTT DoCoMo, Switzerland’s Bluewin, and a whole load more you’ll find here. You frequently wont realise when you’re viewing a PHP-based site, because you’re not forced to use the default .php file extension (PHP often appears as .shtml or phtml).
Also, have a look at the results of this job search — not bad.
And as ezPublish demonstrates, corporations aren’t just using PHP, companies like Siemens are prepared to go into partnership to sell PHP applications to their customers.
10. PHP is doomed!
This is doubtful. In fact in June 2002, PHP overtook ASP to become the first Open Source project to start from behind, and become more popular than the bespoke Microsoft solution. With IIS going into decline against Apache as a result of the Apache 2.0 release and IIS’s poor security record, the gap will only widen.
The .NET framework has only one real edge over PHP, which won’t be making itself apparent for a long time yet: with .NET, you can write an application that will run natively on Windows clients and is delivered from a Website. Microsoft has a long way to go with security before it will be able to unleash that on the Internet — and even when that time comes, browsers and content delivery may be sufficiently advanced to make it irrelevant.
PHP is successful in its own right and in fact is in no way "threatened" by .NET. As to why, your guess is as good as mine, but top of the list might be:
  • its down-to-earth approach to problem solving (PHP has without doubt introduced to programming people who would never have thought themselves capable before),
  • its active and inspired community,
  • its comprehensive and efficient documentation (try this link for example: http://www.php.net/mysql), and
  • the freedom you have as a developer, both in terms of price and choice of code architecture, to do with PHP as you please.
Microsoft would do well to learn some lessons here. PHP.NET would be a start but at the moment Microsoft seems to be ignoring the Internet’s #1 scripting language.
Business as Usual
So there’s a little ammunition for harassed PHP developers. In summary, although .NET has some interesting features, there’s no pressing reason to switch to developing in it. Right now, in terms of web development, Language.NET really only amounts to ASP version 4.0 (with an option of writing in C++ style C#).
If you’re considering Language.NET, it’s worth asking yourself three questions;
  1. "Is there anything here I’m not already doing or capable of doing?"
  2. "Do I want to be forced into a sharp learning curve, a particular coding style and particular strategies for Web development?"
  3. "Do I feel like paying more for hosting?"
In answering those questions, you’ll have a pretty clear idea whether .NET applies to you. And rest assured you’re not "missing out" if you decide it’s not your kettle of fish.
Having said all that, .NET framework is an interesting technology. It incorporates some great concepts, such as multiple language support and has potential for seamlessly integrating the various Microsoft product families. It’s also good that .NET promotes XML standards like XML-RPC and SOAP, which have tremendous potential for the Internet and until recently, have been largely ignored, although XML-RPC has been around since 1999. But there’s a long way to go though before .NET is truly a pervasive technology — and the real showdown for the hearts and minds of developers is not "PHP vs. .NET" but J2EE vs. .NET, which is best left to another article.

PHP vs ASP.net Comparison

PHP vs ASP.net Comparison

A comparison of PHP (Open Source) vs ASP.net (Commercial), Performance, Cost, Scalability, Support and Complexity

There are hundreds of forum debates and articles on the Internet about whether PHP or ASP.net is a better platform. Unfortunately, most opinions are biased and their preference is typically based on promoting one programming language over the other.

Also, if you pay attention to the dates on those articles and debates, you will see that most of the information is outdated and old. This is unfortunate — the debates are showing on top of search engines and the information is no longer valid. We need to consider that there are periodic major upgrades and improvements done to both PHP and ASP.net platforms.

Let me assure you that both programming languages are used in very large web applications and large successful web sites so there should not be any doubt to the ability of any of the above programming languages to handle a large web application project.

In this article:
Regarding performance, I'll explain what factors will effect performance and the result will prove that selecting one programming language over the other because of speed is pointless in most scenarios.

Regarding scalability, I'll explain what factors to consider when it comes to scalability and if programmed correctly, both programming languages are very scalable.

Regarding cost and support, since PHP is open source and commonly runs on an open source platform, LAMP (Linux, Apache, MySQL, PHP), PHP wins over ASP.net for providing the most cost effective solution and providing a large amount of resources and support.

Regarding time to deployment (an additional concern for cost,) on average, it takes twice as much code writing to accomplish something with ASP.net than PHP, so time to deployment is faster using PHP.
I'll go over each of the considerations and also provide my two cents below:

I. Scalability and Ease of Maintenance

Scalability and ease of maintenance have nothing to do with whether you select PHP or ASP.net platform. Web Application scalability and ease of maintenance primarily depend on:
  • Programmers' experience
  • Using the best programming practices
  • Using a solid programming framework
  • Following programming guidelines and standards

II. Performance and Speed

There has been much debate about this subject and most of the debates have been biased and have been tailored to promote one of the programming languages instead of informing the audience.
There are so many other factors to consider when it comes to measuring web application speed, so the speed of any programming language should not have any noticeable effect on the speed and performance of most of the websites today.

However, if the programming language needs to perform enormous tasks similar to the kind that sites such as Google or Yahoo do daily, then there should be a lot of consideration in selecting a very fast programming language for required enormous tasks — that is why Google and Yahoo use several programming languages (mostly open source), each selected to handle the tasks that the programming language is best at performing.

Below, I'm going to analyze the common and uncommon scenarios and explain which task is better than the other:
1st Common Scenario:
One of the common tasks of any web application would be to access and query the database and output the result to the web server and then to the browser. So on this common scenario, all the programming language is doing is communicating / interfacing with the database server and web server. On this common scenario, the speed of the programming language has almost no affect on this process; the speed of this process relies on the database server, web server, client's web browser / computer and bandwidth.
When it comes to the main and common database servers, MySQL (now owned by Oracle), PostgreSQL, MSSQL and Oracle are all fighting for speed and performance. We keep seeing new features and better performance by all database servers in each version upgrade so I will say that the above database servers will all have a great performance if the database programmers use optimized and practical SQL queries and if needed, use the advanced features such as caching.
MySQL is used by Google, Facebook, YouTube, Yahoo and recently on FIFA World Cup which received a huge audience around the World. So I would not question the capability of the MySQL database server.
Based on my research on a few online stats, as of this writing, the communication and interfacing between PHP and MySQL is faster than ASP.net and MSSQL but it is not very noticeable.
2nd Common Scenario:
One of the other common tasks of any web application would be to access the file system, find an image and send it to the web server. In this case, again, the programming language is doing very little — it is the Operating System and the file system that has the burden of communicating with the programming language.

Based on my research on a few online stats, as of this writing, the Linux OS and ext4 (file system) performs better (IO) than Windows OS and NTFS (file system.)

3rd Common Scenario:
Most Linux / Unix servers are run very lean without any extra un-needed packages or GUI interfaces and therefore the OS uses a lot less CPU and RAM which provides more allocation to the database and web server.

Most windows servers run clunky and with many un-needed packages and GUI which will be using much more CPU and RAM.

Obviously, a LAMP platform will have an advantage over the ASP.net platform because it will have more available resources.
4th Not Very Common Scenario:
ASP.net is usually written in C# (pronounced C Sharp) — generally speaking, as of this writing, C# is a faster programming language than PHP. (This may change as each programming language will come up with upgrades to fight for a better speed.) So if the programming language needs to run a 2,000,000 loop execution of a calculation, an ASP.net written in C# will win over PHP. However, this is a very uncommon scenario, the most loop executions of a calculation would be in 100s and not 2,000,000s. And in this case, there should be other concerns about why someone needs to do a 2,000,000 loop calculation.
Additional items that can have an effect on performance but have nothing to do with which programming language is selected are:
  • Ability and knowledge of programmer(s) to optimize the code
  • Ability and knowledge of programmer(s) to write proper and optimized SQL queries.
  • Functionality required (some functions may take longer to execute in the ASP.net platform and less time in PHP platform and vice versa.

III. Cost:

PHP, MySQL server, PostgreSQL server, Apache server, and Linux OS are all free and upgrades are also free. In addition, there is no additional licensing cost for having another hot standby server as a backup, or needing to run multiple servers for load balancing or server clustering.
LAMP (Linux, Apache, MySQL and PHP) is also much more popular among hosting companies, and its popularity results in a lower monthly hosting cost for LAMP hosting compared to Windows hosting.
ASP.net and IIS are free if you purchase Windows OS. There is a substantial licensing cost for a Microsoft Windows Server, Microsoft SQL Server and future upgrades. For example, Microsoft Server 2008 R2 Standard - 64-bit cost is about $1029 and Microsoft SQL Server 2008 Standard Edition For Small Business cost approximately $1038.
The above licensing costs for Microsoft can substantially increase if the site becomes popular and there is a need to run the site on multiple servers or requires server features such as load balancing, server clustering or hot standby.

IV. Support and Resources

Since LAMP is open source, there is a vast amount of dedicated and friendly developers around the world who continuously make improvements and updates, and provide support for the platform. Additionally, there are more support resources and developers available for PHP and LAMP Platforms.
The reason why I mentioned the word "friendly," is because Open Source developers who contribute to the Open Source community are doing so not for financial gain. If you seek help with a functionality challenge and post a question on a PHP forum, you will receive useful information from friendly contributors.
ASP.net relies on an available number of developers at Microsoft for making improvements and updates. There are less support contributors available to solve ASP.net challenges.

V. Time to Deploy

It takes a larger amount (more lines) of code to accomplish complex features and functionality with ASP.net compared to PHP, adding more time to the development process.
Additionally, PHP is interpreted at the server, so when changing a functionality, no additional steps are required to see the changes. On the other hand, ASP.net needs to be compiled each time the code is modified. Again, the development process is more time-consuming when using ASP.net as opposed to PHP.

VI. Editors and Tools

PHP & MySQL is editor independent. PHP developers have access to an extensive number of editors.
Most ASP.net programmers rely on Microsoft Visual Studio editor to help them develop .NET Applications. (Many ASP.net developers love and swear by the Microsoft Visual Studio.)

It is a different style of programming — PHP and open source developers tend to use text editors such as VI, VIM, Notepad ++.

VI and VIM are very advanced and independent editors, and the programmers who learn and use those editors to the fullest capabilities can perform very complex programming, in a fast, efficient and independent way. Those programmers have more control and flexibility, and when it comes to the need of using and integrating other essential platforms, such as JavaScript, Ajax, JQuery, etc., the PHP developers have a better advantage because of their familiarity with the open source environment and hand coding using VI or VIM editors.

VI. Platform Independent

PHP is platform independent and can run on any platform — Linux, Unix, Mac OS X, Windows.
ASP.net is built to run only on Windows platform.

VI. Which popular sites run on which platforms?

The following table lists the top, popular sites and the platform and languages they use.
Note: Please don't confuse C with C# (pronounced C Sharp) — they are completely different programming languages. ASP.net is mostly programmed in C# (C Sharp) or Visual Basic and not C.
Site Up Since Server Platform Programming
Language
Google.com November 1998 Linux C, Java, C++, PHP & MySQL
Facebook.com February 2004 Linux PHP, MySQL and C++
YouTube.com February 2005 Linux C, Java and MySQL
Yahoo.com August
1995
Linux C++, C, Java, PHP & MySQL
MSN.com (owned by Microsoft) August
1995
Windows ASP.net
Live.com (owned by Microsoft) August
2008
Windows ASP.net
Wikipedia January
2001
Linux PHP & MySQL
Amazon.com October
1995
Linux & Solaris C++, Java, J2EE
WordPress.com November
2005
Linux PHP & MySQL

VII. Popularity

The LAMP platform is much more popular than the Windows platform. Based on Netcraft's July 2010 Web Server Survey of 205,714,253 sites, 112,945,968 (54.90%) are hosted on Apache and 53,217,620 (25.87%) are hosted on Windows; the rest are hosted on other platforms.

VII. Usability and Ease of Deployment

There are many misconceptions and misinformation about Linux being unfriendly.
This really depends on the experience and knowledge of the person setting up the platform.
However, I have to say that I'm very impressed with the new and improved versions of popular Linux distributions. These distributions of Linux such as Ubuntu, Red Hat, CentOS, openSUSE, and Fedora have done a great job providing ease of installation and deployment, as well as a simple and straight forward GUI interface that makes configuration and setting up of a Linux server very manageable.
Unfortunately, in my opinion, Microsoft Server has been going backward with usability, by making the server administration extremely clunky and filled with complex and un-needed features.
Research for this article was completed August 1, 2010; pricing and other information may change.

Saturday, 22 June 2013

About Jquery


  • jQuery is a JavaScript Library.

  • jQuery greatly simplifies JavaScript programming.

  • jQuery is easy to learn.

    jQuery Core

    What is jQuery?

     jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript
      

    jQuery

    jQuery Core

    jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
     
    jQuery UI

    jQuery UI

    jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.
    jqueryui.com
     
    jQuery Mobile

    jQuery Mobile

    A unified, HTML5-based user interface system for all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Its lightweight code is built with progressive enhancement, and has a flexible, easily themeable design.

    QUnit

    QUnit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself!
    qunitjs.com

    Sizzle

    A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library.
    sizzlejs.com


    About jQuery UI


    jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.
    There's a lot of work that goes into making jQuery UI the most successful UI library for the Web. Between API design, visual design, implementation, ticket triage, bug fixing, developer relations, infrastructure, and everything else, most of the work is done by volunteers. We'd like to recognize the most prominent contributors below, for a full list of all contributors, see the authors list.


php in_array function

in_arrayChecks if a value exists in an array

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )



Example #1 in_array() example
<?php
$os 
= array("Mac""NT""Irix""Linux");
if (
in_array("Irix"$os)) {
    echo 
"Got Irix";
}
if (
in_array("mac"$os)) {
    echo 
"Got mac";
}
?>

PHP Array Functions

Array Functions

  • array_change_key_case — Changes all keys in an array
  • array_chunk — Split an array into chunks
  • array_column — Return the values from a single column in the input array
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge two or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user function to every member of an array
  • array — Create an array
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key_exists — Alias of array_key_exists
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • natsort — Sort an array using a "natural order" algorithm
  • next — Advance the internal array pointer of an array
  • pos — Alias of current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Alias of count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function

Friday, 14 June 2013

Convert XML to CSV with PHP


PROBLEM : 
I'm using the following code to convert my XML file to a CSV format. Unfortunately, it seems to not be recognizing each entry in the XML and so the XML file ends up being blank.

An example of my XML file is below... Solution :

Thursday, 13 June 2013

Sorting Deep Multidimentional array PHP


Given the following array:
Array 
(
[0] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 4
)

[1] => N/A
[2] => N/A
[3] => N/A
)

[1] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 2
)

[1] => N/A
[2] => N/A
[3] => N/A
)
)
Given the following array:
Array 
(
[0] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 4
)

[1] => N/A
[2] => N/A
[3] => N/A
)

[1] => Array
(
[0] => Array
(
[key1] => var1
[key2] => var2
[sortOnMe] => 2
)

[1] => N/A
[2] => N/A
[3] => N/A
)
)
How can I sort this array considering the key I want is deep in the structure?
I assume usort but not sure what to pass into the function?
 

Ans:

usort($arr, "mysortfunc");

function mysortfunc($a, $b)
{
if ($a[0]['sortOnMe'] == $b[0]['sortOnMe'])
{
return 0;
}
else
{
return ($a[0]['sortOnMe'] < $b[0]['sortOnMe']) ? -1 : 1;
}
}

 

Questions every good PHP Developer should be able to answer, PHP interview Questions

Q: What is T_PAAMAYIM_NEKUDOTAYIM?

A: Its the scope resolution operator (double colon)
An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: *Cause:* body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.  



Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.

Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...

Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.



Q: Given this code:
function doSomething( &$arg )
{
$return
= $arg;
$arg
+= 1;
return $return;
}

$a
= 3;
$b
= doSomething( $a );
 .what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific
Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Q: What is wrong with this code:
class SomeClass
{
protected $_someMember;

public function __construct()
{
$this
->_someMember = 1;
}

public static function getSomethingStatic()
{
return $this->_someMember * 5; // here's the catch
}
}
A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.

Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

Wednesday, 12 June 2013

.height() , jQuery .height()

Get the current computed height for the first element in the set of matched elements or set the height of every matched element.

.height()Returns: Integer

Description: Get the current computed height for the first element in the set of matched elements.
  • version added: 1.0.height()

    • This method does not accept any arguments.
The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.
This method is also able to find the height of the window and document.
1
2


$(window).height(); // returns height of browser viewport




$(document).height(); // returns height of HTML document


Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css("height") rather than .height().
Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block, it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.

Example:


Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28



<!DOCTYPE html>




<html>




<head>




<style>




body { background:yellow; }




button { font-size:12px; margin:2px; }




p { width:150px; border:1px red solid; }




div { color:red; font-weight:bold; }




</style>




<script src="http://code.jquery.com/jquery-1.9.1.js"></script>




</head>




<body>




<button id="getp">Get Paragraph Height</button>




<button id="getd">Get Document Height</button>




<button id="getw">Get Window Height</button>








<div>&nbsp;</div>




<p>




Sample paragraph to test height




</p>




<script>




function showHeight(ele, h) {




$("div").text("The height for the " + ele +




" is " + h + "px.");




}




$("#getp").click(function () {




showHeight("paragraph", $("p").height());




});




$("#getd").click(function () {




showHeight("document", $(document).height());




});




$("#getw").click(function () {




showHeight("window", $(window).height());




});








</script>








</body>




</html>