What is PHP? Write your first PHP Program


What is PHP?

PHP is a server side scripting language. that is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages.

PHP scripts can only be interpreted on a server that has PHP installed.

The client computers accessing the PHP scripts require a web browser only.

A PHP file contains PHP tags and ends with the extension “.php”.

In this tutorial, you will learn-

What is a Scripting Language?

A script is a set of programming instructions that is interpreted at runtime.

A scripting language is a language that interprets scripts at runtime. Scripts are usually embedded into other software environments.

The purpose of the scripts is usually to enhance the performance or perform routine tasks for an application.

Server side scripts are interpreted on the server while client side scripts are interpreted by the client application.

PHP is a server side script that is interpreted on the server while JavaScript is an example of a client side script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into HTML pages.

Programming Language Vs Scripting Language

Programming language Scripting language
Has all the features needed to develop complete applications. Mostly used for routine tasks
The code has to be compiled before it can be executed The code is usually executed without compiling
Does not need to be embedded into other languages Is usually embedded into other software environments.

What does PHP stand for?

PHP means – Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor.

PHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management system and web frameworks.

Php Syntax

A PHP file can also contain tags such as HTML and client side scripts such as JavaScript.

  • HTML is an added advantage when learning PHP Language. You can even learn PHP without knowing HTML but it’s recommended you at least know the basics of HTML.
  • Database management systems DBMS for database powered applications.
  • For more advanced topics such as interactive applications and web services, you will need JavaScript and XML.

The flowchart diagram shown below illustrates the basic architecture of a PHP web application and how the server handles the requests.

Why use PHP?

You have obviously heard of a number of programming languages out there; you may be wondering why we would want to use PHP as our poison for the web programming. Below are some of the compelling reasons.

  • PHP is open source and free.
  • Short learning curve compared to other languages such as JSP, ASP etc.
  • Large community document
  • Most web hosting servers support PHP by default unlike other languages such as ASP that need IIS. This makes PHP a cost effective choice.
  • PHP is regular updated to keep abreast with the latest technology trends.
  • Other benefit that you get with PHP is that it’s a server side scripting language; this means you only need to install it on the server and client computers requesting for resources from the server do not need to have PHP installed; only a web browser would be enough.
  • PHP has in built support for working hand in hand with MySQL; this doesn’t mean you can’t use PHP with other database management systems. You can still use PHP with
    • Postgres
    • Oracle
    • MS SQL Server
    • ODBC etc.
  • PHP is cross platform; this means you can deploy your application on a number of different operating systems such as windows, Linux, Mac OS etc.

What is PHP used for & Market share

In terms of market share, there are over 20 million websites and application on the internet developed using PHP scripting language.

This may be attributed to the points raised above;

The diagram below shows some of the popular sites that use PHP


ASP – Active Server Pages, JSP – Java Server Pages, CFML – Cold Fusion Markup language The table below compares the various server side scripting languages with PHP

Learning curve short Longer than PHP Longer than PHP Longer than PHP
Web hosting Supported by almost all hosting servers Needs dedicated server Fairly supported Needs dedicated server
Open source Yes No Yes Both commercial and open source
Web services support Built in Uses the .NET framework Uses add on libraries Built in
Integration with HTML Easy Fairly complex Fairly complex Easy
MySQL support Native Needs third party drivers Needs third party drivers Current version has native support. Older versions use ODBC
Easily extended by other languages Yes No Extended using Java classes and libraries. Yes

PHP File Extensions

File extension and Tags In order for the server to identify our PHP files and scripts, we must save the file with the “.php” extension. Older PHP file extensions include

  • .phtml
  • .php3
  • .php4
  • .php5
  • .phps

PHP was designed to work with HTML, and as such, it can be embedded into the HTML code.

You can create PHP files without any html tags and that is called Pure PHP file .

The server interprets the PHP code and outputs the results as HTML code to the web browsers.

In order for the server to identify the PHP code from the HTML code, we must always enclose the PHP code in PHP tags.

A PHP tag starts with the less than symbol followed by the question mark and then the words “php”.

PHP is a case sensitive language, “VAR” is not the same as “var”.

The PHP tags themselves are not case-sensitive, but it is strongly recommended that we use lower case letter. The code below   illustrates the above point.

<?php … ?>

We will be referring to the PHP lines of code as statements. PHP statements end with a semi colon (;). If you only have one statement, you can omit the semi colon. If you have more than one statement, then you must end each line with a semi colon. For the sake of consistency, it is recommended that you always end your statement(s) with a semi colon.  PHP scripts are executed on the server. The output is returned in form of HTML.

PHP Hello world

The program shown below is a basic PHP application that outputs the words “Hello World!” When viewed in a web browser.

echo "Hello world";


Hello world


  • PHP stands for Hypertext pre-processor
  • PHP is a server side scripting language. This means that it is executed on the server. The client applications do not need to have PHP installed.
  • PHP files are saved with the “.php” file extension, and the PHP development code is enclosed in tags.
  • PHP is open source and cross platform


Technology Stack for Web Application Development


What’s the most important thing to consider when you’re developing a top-notch web application? No doubt it’s the technology stack your app will be based upon.

The choice of a relevant tech stack is particularly challenging for small businesses and startups, since they usually have limited budgets and, thus, need a technology stack that provides the most bang for the buck to get their projects off the ground.

The right tech stack is, to a great extent, the key to your project’s success, while the wrong choice of web app development technologies may be a reason for failure.

We’ve decided to give you a helping hand and reveal the criteria for choosing the most appropriate tech development stack for your web application.

What Is a Technology Development Stack For Web in 2019?

Before moving on to the criteria for choosing a modern web technology stack, you should clearly understand what comprises the process of web application development.

Without going too deep into details, there are two sides to web development: the client side and the server side. The client side is also called the front end. Server-side programming involves an application (and a backend programming language that powers it), a database, and the server itself.

Client-Side Programming

Client-side (i.e. frontend) web development involves everything users see on their screens. Here are the major frontend technology stack components:

  • Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS). HTML tells a browser how to display the content of web pages, while CSS styles that content. Bootstrap is a helpful framework for managing HTML and CSS.
  • JavaScript (JS). JS makes web pages interactive. There are many JavaScript libraries (such as jQuery, React.js, and Zepto.js) and frameworks (such as Angular, Vue, Backbone, and Ember) for faster and easier web development.

The server side isn’t visible to users, but it powers the client side, just as a power station generates electricity for your house.

The challenge lies mainly in the choice of server-side technologies for developing your web application.

As for server-side programming languages, they are used to create the logic of websites and applications. Frameworks for programming languages offer lots of tools for simpler and faster coding. Let’s mention some of the popular programming languages and their major frameworks (in parentheses):

  • 1.Ruby (Ruby on Rails)
  • 2.Python (Django, Flask, Pylons)
  • 3.PHP (Laravel)
  • 4.Java (Spring)
  • 5.Scala (Play)

Node.js, a JavaScript runtime, is also used for backend programming.

Your web application needs a place to store its data, and that’s what a database is used for. There are two types of databases: relational and non-relational (the latter being subdivided into several categories), each having its pros and cons. Here are the most common databases for web development:

  • 1.MySQL (relational)
  • 2.PostgreSQL (relational)
  • 3.MongoDB (non-relational, document)

A web application needs a caching system to reduce the load on the database and to handle large amounts of traffic. Memcached and Redis are the most widespread caching systems.

Finally, a web application needs a server to handle requests from clients’ computers. There are two major players in this domain:

  • Apache
  • Nginx

To develop a web application, you need to select the server, database, programming language, framework, and frontend tools that you’re going to use. These web development technologies build on top of each other and are, in fact, collectively called a stack.

The Technology Stack at RubyGarage

At RubyGarage, we have found a perfect technology stack for our projects, uniting the best from the web app development. Throughout our work, we’ve managed to figure out which frameworks work better, which SQL data storage fits the projects naturally, and which programming languages are the best fit for a wide range of projects. Altogether, these technologies help us deliver products faster and keep high quality. Depending on your business needs, we can rework a technology stack, for instance, add necessary libraries or frameworks. Below you can find our choice for both frontend and backend web app development.

The Technology Stack at RubyGarage

Now that you have a general understanding of what a web technology stack is, we’d like to draw your attention to the common practices that entrepreneurs and startuppers follow when choosing the technologies for their projects.

Though these practices may sound reasonable, following them may botch up your whole project.

So, what do businesses usually rely on when choosing a technology stack? Here are the most common practices that you should avoid:

#1: Don’t Choose Based on Competitors’ Experiences

Learning from the experience of your competitors may be the right strategy, but not when you’re picking a technology stack. Remember that your project is unique and your ultimate goal is to beat your rival companies.

Therefore, how can you be sure that the tech stacks used by your competitors are truly suitable for your project? If you initially make the wrong choice, you’re likely to face the need to modernize your technology stack in the future, which isn’t cheap.

#2: Don’t Choose Based on Personal Preferences

It’s possible to rely on your personal preferences when choosing a technology stack for a web application. However, there’s a pitfall: this approach works well only for people with a solid background in web development.

For example, if you have relevant experience in web application development or if you’re a chief technology officer, your tech stack preferences may be totally correct. But if you don’t have in-depth knowledge of the web development process, this strategy might lead you to failure, as you are likely to pick the wrong components for your technology stack.

#3: Don’t Choose Based on Previous Projects

No matter how successful your previous projects turned out, you fulfilled them in the past. The technology stack components you used at the time may be outdated now.

Moreover, your projects aren’t the same: the tech stack you use for one project may be inappropriate for another.

#4: Don’t Choose Based on Online Research

Today, the internet is full of surveys, comparisons, and other information that helps you select a technology stack for web applications.

However, there’s a problem: you’re likely to come across sources that will express the exact opposite opinions, providing seemingly strong proofs. Which source should you believe?

Choosing a technology stack is all about practical experience. You can make the right choice only if you’ve applied some technologies and know how well they work. If your knowledge is merely theoretical and based on online research, your chances of picking relevant technologies are very low.

Choosing a tech stack based on internet research only is like trying to fix your car after reading the manual but without having any practical skills. You may do it right, but more likely you’ll have to bear losses for the damage you’ll cause.

Criteria for Choosing a Tech Stack

Having learned what you shouldn’t do when selecting an appropriate tech stack, it’s now time to move on to the core of our article, in other words the criteria you should consider.

Criterion #1: Type of Web Application

The first thing to decide upon is the type of web application you’re developing. A tech stack is a toolset for creating a web app, so you need to fully realize what you’re planning to build in order to pick the appropriate tools. You should find a toolset that provides unique advantages for your web application.

In terms of complexity, all web projects can be divided into three types:

  • Simple. These web applications are created with the help of out-of-the-box solutions (such as CMS software, for example). Examples: landing pages and simple online stores.
  • Mid-level. These apps have more functions than simple apps and are built with the help of frameworks. Examples: apps for large ecommerce stores and enterprises.
  • Complex. These web apps have lots of functions and integrations; they’re developed with the help of different web development technologies and may be composed of several programming languages. Examples: social networks, large ecommerce marketplaces, fintech software, etc.

Knowing the type of web app you’re developing isn’t enough; you should take its business goals into account as well. This is important, since your business goals impact the choice of technologies for development. Your web app can be tailored for:

  • Processing heavy loads. If your web project relies on load processing, you should opt for programming languages and frameworks that can provide this. Examples of such projects are video/audio streaming apps and file sharing services.
  • Low latency. A different tech stack is required to make your web application highly responsive and to reduce latency. Social networks are probably the best example of websites that require low latency.

Criterion #2: Time to Market

Time to market (TTM) is extremely important when choosing a tech stack for startups and for small businesses. The faster you develop and release your application, the more ahead of competitors you’ll be. Moreover, the less time development requires, the cheaper the development cost.

TTM heavily depends on the technology stack you select for your web application, and here’s a list of issues you should consider when choosing a proper stack:

    • Out-of-the-box solutions. Check whether a technology has some out-of-the-box solutions for adding some necessary functionality to your web application. For example, the Ruby on Rails framework allows developers to use lots of open-source libraries (called gems) that facilitate the development process and significantly reduce TTM.
    • Integration with third-party solutions. Make sure the tech stack you choose supports integration with third-party solutions, as it’ll help you add the functions you need to your web application without reinventing the wheel.
    • Developer availability. Even if you’ve decided upon the tech stack, there’s still a problem: you need developers to do all the coding. You should check whether you’ll be able to find developers with expertise in the technology stack you choose. And remember that building a web application is just the beginning. You also need developers to maintain it after launch.
    • Documentation and developer community. Producing good code is difficult, and any development team may stumble over some tricky issues. It may take quite long for a team to find a solution, which means, in turn, a missed web project release deadline. That’s why you should find out whether the technologies you’re going to select have large developer communities and rich documentation.
  • Easy to test. A web application contains many lines of code, so bugs are inevitable. Needless to say, removing all bugs requires a lot of time and slows down development. To counter this problem, choose technologies that are easy to test. Some technologies are based on a so-called test-driven development approach, which implies that testing goes first and coding comes after. Test-driven development allows you to guarantee your code and product quality and speed up development in the medium and long term.

Criterion #3: Web App Development Cost

Needless to say, turning your idea into a real-life web application isn’t free of charge and requires investment. The choice of a website technology development stack has a direct impact on the development cost. There are two main issues you need to take into account:

    • Developer salaries. Web developers are highly skilled professionals who are rather well-paid. Their salaries, however, depend on the technologies they work with. Consequently, your expenses will be different depending on tech stack. You should remember that the more advanced the technology is, the higher the developer salary will be.
  • App maintenance cost. Creating a web application is just one side of the coin; maintaining it is the other. To reduce maintenance costs, you should opt for free open-source technologies. For example, the Ruby on Rails web development framework is available with the MIT licence, which means it can be modified, upgraded, and used without any restrictions

Criterion #4: Security

Our world has gone digital over the last two decades and so have criminals. Cyberattacks are the biggest threat to online businesses: according to a forecast by Juniper Research, annual financial losses from data breaches are expected to reach a mind-blowing $2.1 trillion by 2019. Today, governments and corporations are working hard on ensuring the highest level of cyber security possible.

No doubt, you want your web application to be secure. Hence, you should pick technologies that allow you to create a really secure app. There are lots of different opinions as to which programming language is the safest, but in truth no language guarantees 100% safety.

Every web development technology serves its purpose, so you should choose the right tool first and follow security guidelines second. Most web development technologies have security guidelines where all steps for preventing threats and minimizing vulnerabilities are given. You need to make sure that your web app is created in accordance with the appropriate security guidelines.

Criterion #5: Scalability

Scalability isn’t a feature to turn tail on when developing a web application. No doubt you wish to see your web project grow and gain popularity. In general, there are two kinds of scalability:

  • Horizontal scalability, which means the ability of a web application to accommodate more requests. In other words, an app must be able to work if the number of users grows dramatically.
  • Vertical scalability, which means the ability to add new components to a web application without damaging its performance.

You should think of scalability in advance and choose an appropriate technology stack for your needs. This may seem a difficult choice as you’ll probably come across a number of contradictory opinions. However, we recommend relying not on someone else’s words, but on concrete examples of why exactly a certain technology is scalable.

Technology Stacks Behind Successful Web Projects

By now, you are almost certainly curious about some modern web application stacks. Let’s take a look at what technologies power some of the most successful web projects:

  • Airbnb, the world’s most well-known hospitality service that helps millions of people find rental apartments and short-term lodging, is largely based on Ruby on Rails.
  • Shopify helps entrepreneurs power their online stores. Ruby on Rails is the core technology behind this super-successful web service.
  • Quora is a question-and-answer website where people can find answers to each other’s questions.
  • Instagram, a mainstream social networking application, is built with Python.
  • Product Hunt is a popular service that allows users to share information about products and find new products on the web.
  • Codecademy is an online educational platform that offers free coding classes in 15 programming languages, including Ruby, Python, and Java.
  • Pinterest is a social network aimed at helping people share and find new interests.
Pinterest Tech Stack
  • Reddit is a popular news aggregator and discussion platform.
  • Coursera is a venture-backed educational platform that offers a variety of online courses on different subjects.
  • Facebook is the world’s biggest social network with almost 2 billion active monthly users.

Pick a Technology Stack According to Your Project

As you can see, selecting the right tech stack is a real challenge, but the core idea that should guide you is as follows: choose the technologies according to your project. You shouldn’t rely on time-proven technologies only, even if they have been used by some large and successful companies or prominent projects have been accomplished with their help.

You should always be realistic and take all pros and cons into account. The wrong choice of a technology stack may end in financial losses, so if you aren’t experienced in web development, leave the choice to professionals. A team of professional web developers will be able to choose the right tools for delivering a top-notch web application with all the functionality you need.


9 Useful Browser Extensions for Developers — 2020 Edition

Photo by Luca Bravo on Unsplash
As web developers, we have the luxury of making use of web browser extensions. Web browser extensions are extremely helpful when it comes to enhancing your work environment and boosting coding productivity.

We’re approaching 2020, and many new extensions have popped up. I’ve decided to gather the most useful extensions for web developers and put them in a list.

“If I have seen further it is by standing on the shoulders of giants” — Isaac Newton

1.Refined GitHub

Refined Github simplifies the GitHub interface and adds useful features.

Refined Github
“Our hope is that GitHub will notice and implement some of these much-needed improvements. So if you like any of these improvements, please email GitHub support about doing it.” — Refined Github creators.

Install guide

2.Hacker Tab

Hacker Tab is useful if you’d like to learn about trending open-source projects. Every time you open a new tab, you’ll see a list of all the new projects. You can switch between weekly, daily, and monthly time schedules, and you can also switch between different programming languages.

Hacker Tab — Replace browser new tab screen with GitHub trending projects.

Install guide

3.Daily 2.0 — Source for Busy Developers

Being a brilliant software developer means that you should always strive to learn more and stay updated about the latest technologies out there.

Daily 2.0
Every single day, new and updated software development technologies are being released across the internet. For us as developers, staying updated is a huge hassle. Daily was made by developers for developers to help us focus on code instead of constantly searching for development news around the web.

Install guide

4.No Coin

There are websites out there that force our CPUs to mine cryptocurrencies for them. No Coin is a tiny browser extension aiming to block coin miners, such as Coinhive, who are using your computer resources without your consent.

Trusted by thousands of users, No Coin provides you with a safe and reliable way to block miners from using your CPU and power. No Coin also features an easy way to allow miners for a limited time in case you need to pass a captcha or a short-link that requires mining.

Install guide

5.JSON Formatter

This extension makes JSON easy to read. JSON Formatter is open-source.

JSON Formatter adds a page action to pretty-print JSON. Unlike similar extensions, this simply pretty-prints it. It doesn’t add any kind of viewer, colors, or collapsing.

Install guide

6.Pomodoro Timer

Pomodoro Timer extension
The Pomodoro Technique is a time management method. There are six steps in the original technique:
1.Decide on the task to be done.
2.Set the Pomodoro timer (traditionally to 25 minutes).
3.Work on the task.
4.End work when the timer rings and put a checkmark on a piece of paper.
5.If you have fewer than four checkmarks, take a short break (three to five minutes), and then go to step two.
6.After four Pomodoros, take a longer break (15–30 minutes), reset your checkmark count to zero, and then go to step one.

I’m using Pomodoro as you read this. Pomodoro is a practical way of getting things done, and it helps you learn how to focus and manage your time. If you’re curious to learn more about how to focus, this book was helpful to me.

Install guide

7.Meta SEO Inspector

This extension is useful for inspecting the metadata found inside webpages that’s usually not visible while browsing.

Inspect your meta tags to ensure a good SEO score
This extension is mainly aimed at web developers that need to verify the HTML of their site to follow the Webmasters’ Google Guidelines, but it’s also useful for anyone who wants to see page content that’s not usually visible.
Alerts are shown when the metadata is not within certain ranges — for example when the description tag is too short or too long.
SEO is a language of its own. I suggest reading through “3 Months to No.1: The 2019 “No-Nonsense” SEO Playbook for Getting Your Website Found on Google” for best practices and tips for SEO.

Install guide


Navigate through projects on GitHub efficiently with OctoLinker. OctoLinker turns language-specific statements like include, require, or import into links.

OctoLinker showcase
The source code is on GitHub: https://github.com/OctoLinker/OctoLinker

Install guide


Octotree is an extension that displays a code tree on GitHub. It’s great for exploring project source code without having to download many repositories to your machine.

Install guide


11 JavaScript Tricks You Won’t Find in Most Tutorials


1. Filter Unique Values


The Set object type was introduced in ES6, and along with ..., the ‘spread’ operator, we can use it to create a new array with only the unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];console.log(uniqueArray); // Result: [1, 2, 3, 5]

Before ES6, isolating unique values would involve a lot more code than that!

This trick works for arrays containing primitive types: undefinednullbooleanstring and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)

2. Short-Circuit Evaluation


The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these:

x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’ && and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.

How It Works

Let’s say we want to return just one of two or more options.

Using && will return the first false or ‘falsy’ value. If every operand evaluates to true , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3console.log(0 && null); // Result: 0

Using || will return the first true or ‘truthy’ value. If every operand evaluates to false , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1console.log(0 || null); // Result: null

Example 1

Let’s say we want to return the length of a variable, but we don’t know the variable type.

We could use an if/else statement to check that foo is an acceptable type, but this could get pretty longwinded. Short circuit evaluation allows us to do this instead:

return (foo || []).length;

If the variable foo is truthy, it will be returned. Otherwise, the length of the empty array will be returned: 0 .

Example 2

Have you ever had problems accessing a nested object property? You might not know if the object or one of the sub-properties exists, and this can cause frustrating errors.

Let’s say we wanted to access a property called data within this.state , but data is undefined until our program has successfully returned a fetch request.

Depending on where we use it, calling this.state.data could prevent our app from running. To get around this, we could wrap it in a conditional:

if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';

But that seems pretty repetitive. The ‘or’ operator provides a more concise solution:

return (this.state.data || 'Fetching Data');

We can’t refactor the code above to use && . The statement 'Fetching Data' && this.state.data will return this.state.data whether it is undefined or not. This is because 'Fetching Data' is ‘truthy’, and so the && will always pass over it when it is listed first.

A New Proposed Feature: Optional Chaining

There is currently a proposal to allow ‘optional chaining’ when attempting to return a property deep in a tree-like structure. Under the proposal, the question mark symbol ? could be used to extract a property only if it is not null .

For example, we could refactor our example above to this.state.data?.() , thus only returning data if it is not null .

Or, if we were mainly concerned about whether state was defined or not, we could return this.state?.data .

The proposal is currently at Stage 1, as an experimental feature. You can read about it here, and you can use in your JavaScript now via Babel, by adding @babel/plugin-proposal-optional-chaining to your .babelrc file.

3. Convert to Boolean


Besides the regular boolean values true and false , JavaScript also treats all other values as either ‘truthy’ or ‘falsy’.

Unless otherwise defined, all values in JavaScript are ‘truthy’ with the exception of 0""nullundefinedNaN and of course false , which are ‘falsy’.

We can easily switch between true and false by using the negative operator ! , which will also convert the type to "boolean" .

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define false as !1 is if you were playing code golf!

4. Convert to String


To quickly convert a number to a string, we can use the concatenation operator + followed by an empty set of quotation marks "" .

const val = 1 + "";console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

5. Convert to Number


The opposite can be quickly achieved using the addition operator + .

let int = "15";
int = +int;console.log(int); // Result: 15
console.log(typeof int); Result: "number"

This may also be used to convert booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

There may be contexts where the + will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes: ~~ .

A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to-n — 1 . So, for example, ~15 is equal to -16 .

Using two tildes in a row effectively negates the operation, because — ( — n — 1) — 1 = n + 1 — 1 = n . In other words, ~ — 16 equals 15 .

const int = ~~"15"console.log(int); // Result: 15
console.log(typeof int); Result: "number"

Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans: ~true = -2 and ~false = -1 .

6. Quick Powers


Since ES7, it has been possible to use the exponentiation operator ** as a shorthand for powers, which is faster than writing Math.pow(2, 3) . This is straightforward stuff, but it makes the list because not many tutorials have been updated to include this operator!

console.log(2 ** 3); // Result: 8

This shouldn’t be confused with the ^ symbol, commonly used to represent exponents, but which in JavaScript is the bitwise XOR operator.

Before ES7, shorthand existed only for powers with base 2, using the bitwise left shift operator << :

// The following expressions are equivalent:Math.pow(2, n);
2 << (n - 1);

For example, 2 << 3 = 16 is equivalent to 2 ** 4 = 16 .

7. Quick Float to Integer


If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

The behaviour of | varies depending on whether you’re dealing with positive or negative numbers, so it’s best only to use this shortcut if you’re sure.

If n is positive, n | 0 effectively rounds down. If n is negative, it effectively rounds up. To put it more accurately, this operation removes whatever comes after the decimal point, truncating a float to an integer.

You can get the same rounding effect by using ~~, as above, and in fact any bitwise operator would force a float to an integer. The reasons these particular operations work is that — once forced to an integer — the value is left unchanged.

Remove Final Digits

The bitwise OR operator can also be used to remove any amount of digits from the end of an integer. This means we don’t have to use code like this to convert between types:

let str = "1553"; 
Number(str.substring(0, str.length - 1));

Instead, the bitwise OR operator allows us to write:

console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1

8. Automatic Binding in Classes


We can use ES6 arrow notation in class methods, and by doing so binding is implied. This will often save several lines of code in our class constructor, and we can happily say goodbye to repetitive expressions such as this.myMethod = this.myMethod.bind(this) !

import React, { Component } from React;export default class App extends Compononent {
  constructor(props) {
  this.state = {};
  }myMethod = () => {
    // This method is bound implicitly!
  }render() {
    return (

9. Truncate an Array


If you want to remove values from the end of an array destructively, there’s are faster alternatives than using splice() .

For example, if you know the size of your original array, you can re-define its length property, like so:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;console.log(array); // Result: [0, 1, 2, 3]

This is a particularly concise solution. However, I have found the run-time of the slice() method to be even faster. If speed is your main goal, consider using something like this:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);console.log(array); // Result: [0, 1, 2, 3]

10. Get the Last Item(s) in an Array


The array method slice() can take negative integers, and if provided it will take values from the end of the array rather than the beginning.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

11. Format JSON Code


Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?

The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.

The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

Overall, I hope you found these tips as useful as I did when I first discovered them.

Got any JavaScript tricks of your own? I’d love to read them in the comments below!

12. [Deprecated] Cache Array Length in Loops


In the original version of this article, I shared a tip to cache array length in for loops. However, if it is a read-only loop, modern JavaScript engines deal with this at the point of compilation. It is no longer necessary unless the length of the array changes (and, if that is the case, you’ll probably want it to be recalculated with every iteration anyway).

Thanks to several commenters who pointed this out. If you’d like to find more, check out this question on StackOverflow.

For those who are interested, there used to be some performance incentive to writing for (let i = 0, len = array.length; i < len; i++) rather than for (let i = 0; i < array.length; i++) . This is no longer the case!


Object-Oriented PHP With Classes and Objects


In this article, we’re going to explore the basics of object-oriented programming in PHP. We’ll start with an introduction to classes and objects, and we’ll discuss a couple of advanced concepts like inheritance and polymorphism in the latter half of this article.

Is Object-Oriented Programming (OOP)?

Object-oriented programming, commonly referred to as OOP, is an approach which helps you to develop complex applications in a way that’s easily maintainable and scalable over the long term. In the world of OOP, real-world entities such as Person, Car, or Animal are treated as objects. In object-oriented programming, you interact with your application by using objects. This contrasts with procedural programming, where you primarily interact with functions and global variables.

In OOP, there’s a concept of “class“, which is used to model or map a real-world entity to a template of data (properties) and functionality (methods). An “object” is an instance of a class, and you can create multiple instances of the same class. For example, there is a single Person class, but many person objects can be instances of this class—dan, zainab, hector, etc.

The class defines properties. For example, for the Person class, we might have name, age, and phoneNumber. Then each person object will have its own values for those properties.

You can also define methods in the class that allow you to manipulate the values of object properties and perform operations on objects. As an example, you could define a save method which saves the object information to a database.

A class is a template which represents a real-world entity, and it defines properties and methods of the entity. In this section, we’ll discuss the basic anatomy of a typical PHP class.

The best way to understand new concepts is with an example. So let’s have a look at the Employee class in the following snippet, which represents the employee entity.

class Employee
  private $first_name;
  private $last_name;
  private $age;
  public function __construct($first_name, $last_name, $age)
    $this->first_name = $first_name;
    $this->last_name = $last_name;
    $this->age = $age;
  public function getFirstName()
    return $this->first_name;
  public function getLastName()
    return $this->last_name;
  public function getAge()
    return $this->age;

The class Employee statement in the first line defines the Employee class. Then, we go on to declare the properties, the constructor, and the other class methods.

Class Properties in PHP

You could think of class properties as variables that are used to hold information about the object. In the above example, we’ve defined three propertiesfirst_name, last_name, and age. In most cases, class properties are accessed via instantiated objects.

These properties are private, which means they can only be accessed from within the class. This is the safest access level for properties. We’ll discuss the different access levels for class properties and methods later in this article.

A constructor is a special class method which is called automatically when you instantiate an object. We’ll see how to instantiate objects in the next couple of sections, but for now you just have to know that a constructor is used to initialize object properties when the object is being created.

You can define a constructor by defining the __construct method.

We can think of class methods as functions that perform specific actions associated with objects. In most cases, they are used to access and manipulate object properties and perform related operations.

In the above example, we’ve defined the getLastName method, which returns the last name associated with the object.

So that’s a brief introduction to the class structure in PHP. In the next section, we’ll see how to instantiate objects of the Employee class.

What Is an Object in PHP?

In the previous section, we discussed the basic structure of a class in PHP. Now, when you want to use a class, you need to instantiate it, and the end result is an object. So we could think of a class as a blueprint, and an object is an actual thing that you can work with.

In the context of the Employee class which we’ve just created in the previous section, let’s see how to instantiate an object of that class.

$objEmployee = new Employee('Bob', 'Smith', 30);
echo $objEmployee->getFirstName(); // print 'Bob'
echo $objEmployee->getLastName(); // prints 'Smith'
echo $objEmployee->getAge(); // prints '30'

You need to use the new keyword when you want to instantiate an object of any class along with its class name, and you’ll get back a new object instance of that class.

If a class has defined the __construct method and it requires arguments, you need to pass those arguments when you instantiate an object. In our case, the Employee class constructor requires three arguments, and thus we’ve passed these when we created the $objEmployee object. As we discussed earlier, the __construct method is called automatically when the object is instantiated.

Next, we’ve called class methods on the $objEmployee object to print the information which was initialized during object creation. Of course, you can create multiple objects of the same class, as shown in the following snippet.

$objEmployeeOne = new Employee('Bob', 'Smith', 30);
echo $objEmployeeOne->getFirstName(); // prints 'Bob'
echo $objEmployeeOne->getLastName(); // prints 'Smith'
echo $objEmployeeOne->getAge(); // prints '30'
$objEmployeeTwo = new Employee('John', 'Smith', 34);
echo $objEmployeeTwo->getFirstName(); // prints 'John'
echo $objEmployeeTwo->getLastName(); // prints 'Smith'
echo $objEmployeeTwo->getAge(); // prints '34'

The following image is a graphical representation of the Employee class and some of its instances.

Object Instantiation

Simply put, a class is a blueprint which you can use to create structured objects.

In the previous section, we discussed how to instantiate objects of the Employee class. It’s interesting to note that the $objEmployee object itself wraps together properties and methods of the class. In other words, it hides those details from the rest of the program. In the world of OOP, this is called data encapsulation.

Encapsulation is an important aspect of OOP that allows you to restrict access to certain properties or methods of the object. And that brings us to another topic for discussionaccess levels.

When you define a property or a method in a class, you can declare it to have one of these three access levelspublic, private, or protected.

When you declare a property or a method as public, it can be accessed from anywhere outside the class. The value of a public property can be modified from anywhere in your code.

Let’s look at an example to understand the public access level.

class Person
  public $name;
  public function getName()
    return $this->name;
$person = new Person();
$person->name = 'Bob Smith';
echo $person->getName(); // prints 'Bob Smith'

As you can see in the above example, we’ve declared the name property to be public. Hence, you can set it from anywhere outside the class, as we’ve done here.

When you declare a property or a method as private, it can only be accessed from within the class. This means that you need to define getter and setter methods to get and set the value of that property.

Again, let’s revise the previous example to understand the private access level.

class Person
  private $name;
  public function getName()
    return $this->name;
  public function setName($name)
    $this->name = $name;
$person = new Person();
$person->name = 'Bob Smith'; // Throws an error
$person->setName('Bob Smith');
echo $person->getName(); // prints 'Bob Smith'

If you try accessing a private property from outside the class, it’ll throw the fatal error Cannot access private property Person::$name. Thus, you need to set the value of the private property using the setter method, as we did using the setName method.

There are good reasons why you might want to make a property private. For example, perhaps some action should be taken (updating a database, say, or re-rendering a template) if that property changes. In that case, you can define a setter method and handle any special logic when the property is changed.

Finally, when you declare a property or a method as protected, it can be accessed by the same class that has defined it and classes that inherit the class in question. We’ll discuss inheritance in the very next section, so we’ll get back to the protected access level a bit later.

Inheritance is an important aspect of the object-oriented programming paradigm which allows you to inherit properties and methods of other classes by extending them. The class which is being inherited is called the parent class, and the class which inherits the other class is called the child class. When you instantiate an object of the child class, it inherits the properties and methods of the parent class as well.

Let’s have a look at the following screenshot to understand the concept of inheritance.


In the above example, the Person class is the parent class, and the Employee class extends or inherits the Person class and so is called a child class.

Let’s try to go through a real-world example to understand how it works.

class Person
  protected $name;
  protected $age;
  public function getName()
    return $this->name;
  public function setName($name)
    $this->name = $name;
  private function callToPrivateNameAndAge()
    return "{$this->name} is {$this->age} years old.";
  protected function callToProtectedNameAndAge()
    return "{$this->name} is {$this->age} years old.";
class Employee extends Person
  private $designation;
  private $salary;
  public function getAge()
    return $this->age;
  public function setAge($age)
    $this->age = $age;
  public function getDesignation()
    return $this->designation;
  public function setDesignation($designation)
    $this->designation = $designation;
  public function getSalary()
    return $this->salary;
  public function setSalary($salary)
    $this->salary = $salary;
  public function getNameAndAge()
    return $this->callToProtectedNameAndAge();
$employee = new Employee();
$employee->setName('Bob Smith');
$employee->setDesignation('Software Engineer');
echo $employee->getName(); // prints 'Bob Smith'
echo $employee->getAge(); // prints '30'
echo $employee->getDesignation(); // prints 'Software Engineer'
echo $employee->getSalary(); // prints '30K'
echo $employee->getNameAndAge(); // prints 'Bob Smith is 30 years old.'
echo $employee->callToPrivateNameAndAge(); // produces 'Fatal Error'

The important thing to note here is that the Employee class has used the extends keyword to inherit the Person class. Now, the Employee class can access all properties and methods of the Person class that are declared as public or protected. (It can’t access members that are declared as private.)

In the above example, the $employee object can access getName and setName methods that are defined in the Person class since they are declared as public.

Next, we’ve accessed the callToProtectedNameAndAge method using the getNameAndAge method defined in the Employee class, since it’s declared as protected. Finally, the $employee object can’t access the callToPrivateNameAndAge method of the Person class since it’s declared as private.

On the other hand, you can use the $employee object to set the age property of the Person class, as we did in the setAge method which is defined in the Employee class, since the age property is declared as protected.

So that was a brief introduction to inheritance. It helps you to reduce code duplication, and thus encourages code reusability.

Polymorphism is another important concept in the world of object-oriented programming which refers to the ability to process objects differently based on their data types.

For example, in the context of inheritance, if the child class wants to change the behavior of the parent class method, it can override that method. This is called method overriding. Let’s quickly go through a real-world example to understand the concept of method overriding.

class Message
  public function formatMessage($message)
    return printf("<i>%s</i>", $message);
class BoldMessage extends Message
  public function formatMessage($message)
    return printf("<b>%s</b>", $message);
$message = new Message();
$message->formatMessage('Hello World'); // prints '<i>Hello World</i>'
$message = new BoldMessage();
$message->formatMessage('Hello World'); // prints '<b>Hello World</b>'

As you can see, we’ve changed the behavior of the formatMessage method by overriding it in the BoldMessage class. The important thing is that a message is formatted differently based on the object type, whether it’s an instance of the parent class or the child class.

(Some object-oriented languages also have a kind of method overloading that lets you define multiple class methods with the same name but a different number of arguments. This isn’t directly supported in PHP, but there are a couple of workarounds to achieve similar functionality.)


20 Essential CSS Tricks Every Designer Should Know


1. Absolute positioning

If you want control over where an element lives on our website at all times, absolute positioning is the key to making this happen. If you think of your browser as one big bounding box, absolute positioning allows you to control exactly where in that box an element will stay. Use top, right, bottom and left, accompanied by a pixel value to control where an element stays.


The CSS above sets the position of an element to stay 20px from the top and right edges of your browser. You can also use absolute positioning inside of a div.

2. * + selector
The * enables you to select all elements of a particular selector. For example, if you used *p and then added CSS styles to that, it would do it to all elements in your document with a <p> tag. This makes it easy to target parts of your website globally.

3. Overriding all styles
This should be used sparingly, because if you do this for everything, you’re going to find yourself in trouble in the long run. However, if you want to override another CSS style for a specific element, use !important after the style in your css. For example, if I wanted the H2 headers in a specific section of my site to be red instead of blue, I would use the following CSS:

.section h2 { color:red !important; }

4. Centering
Centering is tricky, because it depends on what you’re trying to center. Let’s take a look at the CSS of items to be centered, based on content.


Text is centered using the text-align:center;. If you want it to either side, use left or right instead of center.


A div (or any other element) can be centered by adding the block property to it, and then using auto margins. The CSS would look like this:

#div1 {
    display: block;
    margin: auto;
    width: anything under 100% 

The reason I put “anything under 100%” for width is because if it was 100% wide, then if would be full-width and wouldn’t need centering. It is best to have a fixed width, like 60% or 550px, etc.

5. Vertical alignment (for one line of text)
You will use this in a CSS navigation menu, I can almost guarantee that. The key is to make the height of the menu and the line-height of the text the same. I see this technique a lot when I go back and edit existing websites for clients. Here’s an example:

.nav li{

6. Hover effects
This is used for buttons, text links, bock sections of your site, icons, and more. If you want something to change colors when someone hovers their mouse over it, use the same CSS, but add :hover to it and change the styling. Here’s an example:

.entry h2{

.entry h2:hover{

What this does is it changes the color of your h2 tag from black to red when someone hovers over it. The great thing about using :hover is that you don’t have to declare the font-size or weight again, if it isn’t changing. It only changes what you specify.


For hover effects, like with menus or on images in your website, you don’t want colors snapping too quickly to the end result. You ideally want to ease the change in gradually, which is where the transition property comes into play.

.entry h2:hover{
    transition: all 0.3s ease;

This makes the change happen over .3 seconds, instead of just instantly snapping to red. This makes the hover effect more pleasing to the eye and less jarring.

7. Link states
These styles are missed by a lot of designers, and it really causes usability issues with your visitors. The :link pseudo-class controls all links that haven’t been clicked on yet. The :visited pseudo class handles the styling of all of the links you’ve already visited. This tells website visitors where they have already been on your site, and where they have yet to explore.

a:link { color: blue; }
a:visited { color: purple; }

8. Easily resize images to fit
Sometimes you get in a pinch where images need to fit a certain width, while scaling proportionally. An easy way to do this is to use max width to handle this. Here is an example:

img {

This means that the largest the image could ever be is 100%, and the height is automatically calculated, based on the image width. In some cases, you might have to also have to specify the width at 100%.
9. Control the elements of a section
Using the image example above, if you only want to target the images of a certain section, like your blog, use a class for the blog section, and combine it with the actual selector. This will enable you to select only the images of the blog section, and not other images, such as your logo, or social meia icons, or images in any other sections of your site, like the sidebar. Here’s how the CSS would look:

.blog img{

10. Direct children
I wish I’d known this when I first started out using CSS. This would have saved me so much time! Use > to select the direct children of an element. For example:

#footer > a

This will select and style all of the active link elements that are immediately under the Footer ID. It won’t select anything past the active element, or anything else contained in the footer, like plain text. This works great with top level navigation elements, too.

Specific Child Elements

Believe me, this is handy when you are styling lists. You just need to count how many items down the element is that you want to style and then apply that style.

li:nth-child(2) {
    color: blue;

The CSS above targets the second item in the list and makes it bold, underlined, and blue. Add an “n” after the number in parenthesis and you can target every 2nd list item. Imagine being able to style every other line in a table-style layout for easy reading. The CSS would be:


11. Apply CSS to multiple classes, or selectors
Let’s say you wanted to add an identical border around all images, the blog section and the sidebar. You don’t have to write out the same exact CSS 3 times. Just list those items out, separated by commas. Here is an example:

.blog, img, .sidebar {
    border: 1px solid #000;

Whether you’ve been a web designer for years, or you’re just starting out, learning how to build websites the right way can seem like a rocky, never-ending journey. Once you’ve narrowed down which languages you want to learn, you have to learn and refine your skills.

No matter what you learn, CSS is one of those essential, but daunting skills you have to master. It doesn’t have to be so difficult, though, especially if you know a few handy and lesser-known CSS techniques to get the job done.

12. box-sizing: border-box;
This is a favorite among many web designers, because it solves the problem of padding and layout issues. Basically, when you set a box to a specific width, and add padding to it, the padding adds to the size of the box. However, with box-sizing:border-box;, this is negated, and boxes stay the size they are meant to be.

13. :before
This CSS is a selector that allows you to choose a CSS element and insert content before every element with a specific class applied to it. Let’s say you had a website where you wanted specific text before every H2 tag. You would us this setup:

h2:before { 
    content: "Read: ";
<span class="Apple-converted-space">    color: #F00;</span>

This is extremely handy, especially if you are using an icon font. You can place icons before certain elements, and apply it globally.

14. :after
Like the :before selector, you can use :after to insert content globally on specific elements. A practical use would be adding “read more” after every excerpt on a blog. Here’s how you would do that.

    content: " -Read more… ";

15. content
content is a CSS property that comes in handy when you need to insert an element that you want to be able to control. The most common use I’ve seen for this is to insert an icon from an icon font in a specific place. In the examples above, you can see that you have to wrap the text you want to insert in quotation marks.

16. CSS reset
Different browsers have default CSS settings, so it is a must to reset those, so you have an even, consistent playing field. Think of it as building a house, and whether you build on the side of a mountain, on a sandy beach, or on the middle of a wooded area, you want that foundation to be level.

This CSS reset method sets a standard base for all of your websites, giving them consistency in their CSS starting point. It removes unwanted borders, preset margins, padding, lines heights, styles on lists, etc. Eric Meyer created one that works well.

17. Drop caps
Everyone loves drop caps. It reminds us of the traditional printed book, and is a great way to start a page of content. That 1st, large letter really grabs your attention. There’s an easy way to create a drop cap in css, and it’s by using the pseudo element: :first letter. Here’s an example :


What this does is set the letter to 3x the size of the other letters. It sets 3px of space around the letter to prevent overlapping, and sets the color of the letter to red.

18. Force text to be all caps, all lowercase, or capitalized
It would be absurd to type an entire section in all caps. Imagine having to go back and fix that later when the format of the website changes, or it gets updated. Instead, use the following css styles to force text to a certain formatting. This css targets the h2 title tag.

  • h2 { text-transform: uppercase; } – all caps
  • h2 { text-transform: lowercase; } – all lowercase
  • h2 { text-transform: capitalize; } – capitalizes the 1st letter of each word.

19. Vertical screen height
Sometimes you want a section to fill the entire screen, no matter what the screen size is. You can control this with vh, or view height. The number before it is a percentage, so if you want it to fill 100% of the browser, you would set it to 100. You might set it to a value like 85% to accommodate a fixed navigation menu.

Create a class for the container and apply the amount of vh you want it to have. One thing you may need to tweak is the media query value for specific screens or orientations like phones in portrait mode. Imagine stretching a landscape image to fit portrait mode. That just wouldn’t look good.

.fullheight { height: 85vh; }

20. Style telephone links
If you have a link that calls a phone number when a user taps it on their phone, you may have trouble styling it with the traditional active link selector. Instead, use the following CSS:

a[href^=tel] {
<span class="Apple-converted-space">    color: #FFF;</span>
<span class="Apple-converted-space">    text-decoration: none;</span>