Tuesday, November 30, 2021

PHP Type Casting: A Complete Guide

PHP Type Casting: A Complete Guide

When you are writing a program, you will need to create and manipulate multiple variables. These variables might store the same or different types of data. For example, some of them could have an integer value while others could be a string or float.

Different programming languages have their own set of rules for defining and declaring variables. A language like C++ needs you to specify the type of variable before you can start using it and won't implicitly convert it to some other type. PHP, on the other hand, has somewhat relaxed rules around types. You don't have to specify the type of value that you will store in a variable beforehand. It also allows you to store a different kind of value in the same variable without any explicit type conversion at a later point.

PHP does this type conversion for you automatically based on the context in which a variable is used. In this tutorial, you will learn what rules are followed for this type conversion and how you can do type casting explicitly whenever needed.

Allowed Type Casts in PHP

You can cast one type of values into another by adding your desired type in parenthesis before the variable that you want to cast.

There are six main type casts allowed in PHP. These are listed below:

  • cast to int by using (int) or (integer)
  • cast to bool using (bool) or (boolean)
  • cast to float using (float), (double) or (real)
  • cast to string using (string)
  • cast to array using (array)
  • cast to object using (object)

Two additional type casts are binary casting and null casting. In previous versions of PHP, you could cast a variable to NULL by prefixing it with (unset). However, this has been deprecated since PHP 7.2.0 and removed since PHP 8.0.0. The binary casting exists for forward support and for now it behaves the same as (string). However, things may change in the future so I wouldn't advice you to rely on this behavior.

Casting Values to Boolean

A boolean can only have two possible values. It will either be true or false. Boolean values are generally passed to control structures to modify the flow of a program. You can cast any variable to a boolean by prefixing it with (bool) or (boolean). However, this isn't always necessary because PHP can determine from the context if you want a value to be evaluated as a boolean.

The boolean false itself naturally evaluates to false. The integer value 0, float values 0.0 and -0.0, an empty string as well as the string "0", an array with zero elements and the type NULL are all considered false when converting a value to boolean. Additionally, SimpleXML objects that are created from empty elements with no attributes also evaluate to false.

Every other value will evaluate to true. This also includes the string "false" and integer values like -1.

Initial Value Cast to Boolean
false false
"false" true
0 false
"0" false
"zero" true
"" false
-1 true
"empty" true
"null" true
array() false

As you can see, only the empty string and the string "0" evaluate to false, every other string like "zero", "empty", "false" or "null" evaluates to true.

Casting Values to Integers

You can cast any variable into an integer by prefixing it with (int) or (integer). Another way to convert a value to integer is to use the intval() function. Usually, you won't need to explicitly make these conversions because PHP will look at the context in which the variable is being used and convert it automatically if needed.

There are certain rules about integer conversion that you should keep in mind to avoid any unexpected surprises.

  1. A boolean false becomes 0 and a boolean true becomes 1.
  2. Floating point numbers will always be rounded towards zero.
  3. NaN and Infinity always evaluate to zero when cast to int.
  4. A string which is either fully numeric or leading numeric is converted to corresponding numeric values. All other strings evaluate to zero.
  5. The value null is always converted to zero.
Initial Value Cast to Int
false 0
true 1
"-1" -1
"null" 0
"twenty" 0
"20.855 apples" 20
"1.2e8" 120000000
12.7 12
-5.9 -5

Two things to observe here are the conversion of string "twenty" to 0 and the conversion of "20.855 apples" to 20. In this second string, the decimal part was dropped because we are casting to integers.

Casting Values to Floats

Floats or floating point numbers are also known as doubles or real numbers. Unlike int which can only store integers and not decimals, a float can store all types of numbers. You can cast any variable into a float by adding (float), (double) or (real) before it.

There are only two rules that you need to remember about casting of values to floats.

  1. A numeric or leading numeric string will resolve to corresponding float value. All other strings will be evaluated to zero.
  2. All other types of values are first converted to integers and then to a float.
Initial Value Cast to Float
false 0
true 1
"-1" -1
"null" 0
"twenty" 0
"20.855 apples" 20.855
"1.2e8" 12000000

This time the entire number 20.855 was retained because the string is being cast into a float and floats  can represent the decimal part of a number.

Casting Values to Strings

You can convert any value to a string either by adding (string) before it or by calling the strval() function. PHP also does this conversion automatically for expressions which expect a string. This includes things like calling echo or comparing a variable to a string.

Conventions followed by PHP when converting anything to a string are listed below.

  1. A false boolean value becomes an empty string and a true value becomes the string "1".
  2. Integers and floats are converted to textual representation of those numbers.
  3. All arrays are converted to the string "Array".
  4. The value NULL is always converted to an empty string.
  5. Objects are converted to a string with the help of the __toString() magic method.
  6. Resources are converted to strings based on the format "Resource id #X" where X is a number like 1,2,3 etc. assigned to the resource by PHP at runtime.

As you can see, converting an array, object or resource to a string does not yield any useful results. You should consider using functions like var_dump() if you want to see the data stored inside these types of values.

Initial Value Cast to String
false ""
true "1"
"false" "false"
0 "0"
1.24984e8 "124984000"
-38 "-38"
["Apple", "Monkey", 38] "Array"
[] "Array"
null ""

Casting Values to Arrays

An array is used to store a bunch of elements to be accessed later. Arrays can contain zero, one or more elements. Therefore, converting values of type integer, float, string, bool and resource creates an array with a single element. The element can be accessed at the index zero within the new array.

Casting a NULL into an array will give you an empty array.

Initial Value Cast to Array
false [false]
true [true]
"false" [false]
"apple" ["apple"]
12984000
[12984000]
-38 [-38]
null
[]

Casting an Object to an Array

Conversion of objects to arrays is a bit more complicated. The elements of the final array are the object's properties. The keys of those elements are derived from the member variable names based on the following rules.

  1. Class names are prepended to private variable names. A NUL byte is appended on both sides of the prefix.
  2. An asterisk (*) is prepended to protected variable names. A NUL byte is appended on both sides of the prefix in this case as well.
  3. Public variable names are directly used as keys.

As you can see in the above example, the NUL byte is not evident when you simply use var_dump() but it is actually present inside the arrays' keys.

Casting Values to NULL, Resources or Objects

In earlier versions of PHP, you could cast a value to NULL by prefixing it with (unset). However, this has been removed from PHP 8.0.0.

Resource variables are used to store a reference to some external resource. These can be opened files, database connections or images etc. Resources provide us a way to access external objects internally. Therefore, it doesn't make any sense to convert arrays, string or floats in PHP to resources.

Casting an integer, float, array or string into an object results in creation of a new instance of the built-in PHP class stdClass. A value of null results in an empty new instance.

Conversion of an array into an object is done with keys considered as property names and their corresponding values as the value of those properties.

All other types of values are cast into an object with a member variable named scalar that stores the value.

Final Thoughts

In this tutorial, we have tried to cover all the basics of type casting in PHP. We began the tutorial by mentioning that PHP can automatically handle type conversion in most situations where it is required. Then we listed different types that you are allowed to cast values into in PHP. However, PHP follows certain rules when doing all this type casting. Keep them in mind and you will avoid some unexpected surprises.


Functional Programming in PHP With Lambda Functions

Functional Programming in PHP With Lambda Functions

One of the nice things about programming is that the same problem can be solved using multiple methods. This allows people to show their creativity and come up with incredibly efficient and unique solutions. Example of this can be seen in action when you look for programs that list or find prime numbers.

Similarly, there are different styles of writing a program. Two common types of styles are functional programming and object-oriented programming. The functional style of programming is based on dividing tasks into separate functions. These functions take some arguments and then return a single value. The returned value is based only on the provided input.

This tutorial will teach you how to use functional programming in PHP with lambda functions.

Functional Programming in PHP

Functions are used in programming to group bunch of instructions together that act on optional input to produce some result. There is a special class of functions called first-class functions where a programming language treats its functions as first-class citizens. In simple terms, this means that functions in those programming languages can be passed around as arguments to other functions or used as return values as well as assigned to other variables.

The support for first-class functions was introduced in PHP with version 5.3. This allows us to create anonymous functions (also called lambdas) and closures in PHP. In this tutorial, you will learn all the important concepts that you need to know about lambda functions in PHP.

Anonymous or Lambda Functions in PHP

The use of terms anonymous functions and lambda functions interchangeably can be confusing for people because the PHP manual does not use the term lambda functions anywhere in their entry about anonymous functions. However, dig a bit deeper and you will find an RFC page about closures that discusses lambda functions.

The usefulness of lambda functions can be best understood with the help of some examples. As you already know, there are some built-in functions in PHP that accept other functions as arguments. These callback functions act on provided data and produce a final result. For example, the array_map() function which accepts a callback function as its first parameter.

Without lambda functions, you will be limited to one of the following three options:

  1. Define the function somewhere else and then refer to it inside array_map() by its name. This will force you to move back and forth in your file to see the function definition whenever needed.
  2. Define the callback functions inside array_map() and specify a name. However, you will still need to check that there is no name clash by using function_exists().
  3. Just create the function at run time using create_function() in PHP. This might seem like a good idea at first but it isn't. It can result is lower readability, performance drop and security issues. In fact, PHP 8.0.0 has removed create_function() from the language.

Lambda or anonymous functions get rid of all these drawbacks by allowing you to define functions in-place without requiring a name. They also compile before runtime so you don't get any performance drop.

Here is an example of anonymous functions in PHP:

In the above example, we create a new array with squares of original numbers using array_map(). As you can see, there was no need to specify a unique name for the callback function and its definition was provided in-place so we didn't have to jump around to see what it does.

Understanding Closures in PHP

Closures are basically lambda functions that can access variables in their parent scope. We have already covered the basics of variable scope in PHP in an earlier tutorial. This increases the usefulness of closures by allowing us to write more flexible and general-purpose functions.

Lets try to rewrite the function in previous section so that it can calculate the exponentiation value to any number instead of just 2. At first, you might try to write it in the following manner:

This will give you a warning about an undefined variable $pow and output an array with the wrong values. You can solve this problem by using the global keyword to access the variable inside the callback function. However, that approach has its own drawbacks which I have already discussed in the tutorial about variable scope.

PHP has a special keyword called use that gives you access to the variables in parent scope. These lambda functions which take advantage of the use keyword to access variables that are outside their scope are called closures. The following code example illustrates their use:

One important thing to remember is that variables are passed inside the function as values. This means that any changes you make to a variable from parent scope will not be visible outside the closure. Here is an example:

In the above example, we go through the for loop 3 times and then increment the value of $calls by 1 during each of the five calls to our anonymous function. Therefore, the final value of $calls should have been 15. However, it simply stays at 0.

One way to make the value of $calls stick across iterations as well as outside the closure is to pass it as a reference.

Arrow Functions in PHP

Arrow functions were introduced in PHP 7.4 and they simply provide us a way of writing our anonymous or lambda functions more concisely. They take the concept of closures one step further and automatically pass all the variables from the parent scope to the scope of our lambda function. This means that you no longer need to import variables with the use keyword.

Keep in mind that the variables are passed by value instead of reference by default. You can still pass them by reference if you want.

Higher Order Functions

Those functions which either take a function as an argument or return a function as their value are called higher order functions. As we learned in the beginning of this tutorial, PHP has proper support for first-class functions. This means that we can also write our higher order functions in PHP.

Let's use everything we have learned so far to create a higher order function that generates simple sentences from passed values.

The above function accepts a single parameter that specifies the topic for generation of our sentences. Inside the function, we use some conditional statements to return an arrow function which in turn returns a concatenated string.

We will now create three different arrays that contain names of people, fruits and planets. These arrays will be passed two at a time to the array_map() function along with our function make_sentences() as callback.

As you can see, we were able to generate some simple sentences by taking corresponding elements from two different arrays and joining them in a string. You should try introducing an additional variable inside the make_sentences() function which will then be used in the arrow functions to create slightly more complicated sentences.

Final Thoughts

We have covered many topics in this tutorial which are related to each other in one way or another. Starting with a brief introduction of functional programming in PHP. We moved on to some useful language features in PHP like lambdas or anonymous functions, closures, and arrow functions. You should now have a good idea of all these terms and how they are different but still related to each other. Finally, we learned how to create our own higher order functions in PHP.

All these concepts will hopefully help you write safer and cleaner code in your future projects.


15+ Best WooCommerce Themes for Amazon Affiliates in 2022

15+ Best WooCommerce Themes for Amazon Affiliates in 2022

If you’ve found this article, chances are you’re considering adding or updating Amazon affiliates to your website! Read on for my pick of 15+ of the best WooCommerce Amazon themes in 2022, as well as some all-important info on how these themes work. 

How Do WooCommerce Themes Work?

WooCommerce is an eCommerce plugin for WordPress, meaning you can sell products quickly and easily from your WordPress website. If you’re yet to try, here’s how they work: 

  • Head to Envato Market where you can scroll through a huge variety of themes on ThemeForest. 
  • If you’re looking to integrate your WooCommerce site with Amazon, just search for ‘Amazon’ themes and you’ll find loads of themes ranging from fashion layouts to tech. 
  • Pick your favorite and download the theme. 
  • Customize the template with your own words, images, and products to make the site your own. 

Why Pick WooCommerce Themes?

There are a whole host of reasons to pick a WooCommerce theme, including the 3 points below!

  1. Simplicity: No matter your level of technical expertise, WooCommerce has been designed to be quick and easy to use. 
  2. Popularity: WooCommerce is a popular plugin—and one that gets lots of attention! It’s updated regularly so you don’t need to worry about getting left behind. 
  3. Flexibility: There are so many WooCommerce themes out there, which will mean you’re spoiled for choice when it comes to picking a compatible theme that will work well for your business. 

How Do WooCommerce Themes Work With Amazon Affiliates? 

Rather than simply selling your own products on your website, you can consider introducing affiliates. For example, you could partner up with another business and provide links to their products on Amazon. You can then earn a commission by promoting these products on your page.

The affiliated seller benefits from increased eyeballs on their products and you can generate additional revenue—win, win.

How Can WooCommerce Amazon Affiliates Themes Help Your Business? 

Whether you’re just starting out or are looking to grow your business, using an Amazon affiliates theme can help your business in plenty of ways. 

  • Professionalism: Setting up a website by using a theme can help to show current and potential customers you mean business. 
  • Financial: As mentioned previously, your new site won’t just look good—it’ll do good things for your bank balance. By showing visitors affiliated Amazon products, you can take a slice of the sales. 
  • Keep Shoppers Interested: Perhaps you don’t have your own products to sell just yet or maybe you never plan to. By working with Amazon affiliates, you can keep your fanbase interested without the hassle or start-up costs. 

15+ Best WooCommerce Themes for Amazon Affiliates in 2022

From art to cosmetics, read on for my pick of 15+ of the best WooCommerce themes for Amazon affiliates. 

1. Affiliate - WooCommerce Amazon Affiliates Theme

Affiliate - WooCommerce Amazon Affiliates ThemeAffiliate - WooCommerce Amazon Affiliates ThemeAffiliate - WooCommerce Amazon Affiliates Theme

One great thing about WooCommerce Amazon themes is their versatility—and this one’s no exception! Take a look at the 12 theme demos to see how the theme can be adapted based on your business. There’s a theme for businesses including eCommerce shops, bookstores, game sellers, crypto sellers—and loads more. 

2. Kingdom - WooCommerce Amazon Affiliates Theme

Kingdom - WooCommerce Amazon Affiliates ThemeKingdom - WooCommerce Amazon Affiliates ThemeKingdom - WooCommerce Amazon Affiliates Theme

Published back in 2016, this Amazon pay WooCommerce has experience on its side. It’s still updated regularly though and has all the latest features, like being Gutenberg-optimized for easy editing. You can bring Amazon products to the forefront with the browsing history widget, custom shop filters, and full-page related products. 

3. Zass - WooCommerce Theme for Handmade Artists and Artisans

Zass - WooCommerce Theme for Handmade Artists and ArtisansZass - WooCommerce Theme for Handmade Artists and ArtisansZass - WooCommerce Theme for Handmade Artists and Artisans

Designed with artists and artisans in mind, you can show off wares with product-centric pages, a useful ‘quick view’ feature, and coupon integration. Check out the reviews and you can see the Amazon theme WooCommerce is consistently rated highly for design quality. There’s also a useful marketplace sellers dashboard, which helps vendors manage products, track orders, and more. 

4. Digic – Electronics Store WooCommerce Theme

Digic – Electronics Store WooCommerce ThemeDigic – Electronics Store WooCommerce ThemeDigic – Electronics Store WooCommerce Theme

If you’re building or updating your electronics store, then this handy WooCommerce affiliate Amazon theme has your name on it.

There are 11 homepage demos with another on the way—each designed in a way to put products front and center. Like many of the best WooCommerce Amazon affiliates themes, it’s fully responsive so will work seamlessly across any device. 

5. Dimita – Electronics WordPress Theme for WooCommerce

Dimita – Electronics WordPress Theme for WooCommerceDimita – Electronics WordPress Theme for WooCommerceDimita – Electronics WordPress Theme for WooCommerce

Enter another WooCommerce integration that’s perfect for your electronics store! With 12+ homepages, you can see the flexibility Dimita offers. The well-organized product pages also show that you don’t need to jeopardize quality when introducing affiliate links into your website.

It comes packed with features—from unlimited colors and layouts, to 12-banner-effect support, to social sharing features, to SEO optimization. 

6. Pustaka – WooCommerce Theme for Book Store

Pustaka – WooCommerce Theme for Book StorePustaka – WooCommerce Theme for Book StorePustaka – WooCommerce Theme for Book Store

As the name suggests, this is a theme designed especially for book stores! If you’re looking to become a WooCommerce Amazon seller, then this makes your life a whole lot easier as you can include well-organized book pages and author pages with direct links to Amazon. The demo makes the most of subtle animations which help to draw the eye to important sections. 

7. Handy – Handmade Items Marketplace Theme

Handy – Handmade Items Marketplace ThemeHandy – Handmade Items Marketplace ThemeHandy – Handmade Items Marketplace Theme

This WooCommerce Amazon theme is crafted with handmade gifts in mind, and selling products through marketplaces like Etsy or Amazon.

For a more handmade feel, you can set custom layouts on each of the static pages, blog, and shop pages. You can keep sliders updated too to share news, products, and company updates. 

8. Wooxon – WooCommerce WordPress Theme

Wooxon – WooCommerce WordPress ThemeWooxon – WooCommerce WordPress ThemeWooxon – WooCommerce WordPress Theme

Do you have a wide variety of products available? If so, this Amazon theme WooCommerce is definitely one to consider. You can include a large navigation bar to organize your affiliate product links. If you’d like, you can also opt for one of the well-designed demos—there’s one for furniture, for example, and another for electronics. 

9. Spozy - Multipurpose WooCommerce Theme

Spozy - Multipurpose WooCommerce ThemeSpozy - Multipurpose WooCommerce ThemeSpozy - Multipurpose WooCommerce Theme

Similarly to Wooxon, Spozy is an Amazon pay WooCommerce theme that you’re not going to want to miss. Check out the 10+ homepage demos for a taster of what your website could look like. Furniture, beds, sport, decor, fashion, bags—there are loads of options.

Check out the Bed demo’s homepage, for example, to see the beauty of simplicity in action. From a full-width header to explain latest products and offers, to a bestsellers list, to the deal of the week, to an Instagram link, to latest news. 

10. Tokoo – Electronics Store WooCommerce Theme for Affiliates, Dropship and Multi-vendor Websites

Tokoo – Electronics Store WooCommerce Theme for Affiliates, Dropship and Multi-vendor WebsitesTokoo – Electronics Store WooCommerce Theme for Affiliates, Dropship and Multi-vendor WebsitesTokoo – Electronics Store WooCommerce Theme for Affiliates, Dropship and Multi-vendor Websites

This product-filled WooCommerce Amazon seller is just the job if you have loads of products to sell! Take a look at Home V1, for example, and you’ll see products can be organized according to different categories, i.e. ‘deals of the day’, ‘best-rated products’, ‘new arrivals’ and ‘best sellers’. You can also use icons to let the user know the product is on sale. 

11. Armania – Fashion, Furniture, Organic, Food Multipurpose Elementor WooCommerce Theme (RTL Supported)

Armania – Fashion, Furniture, Organic, Food Multipurpose Elementor WooCommerce Theme (RTL Supported)Armania – Fashion, Furniture, Organic, Food Multipurpose Elementor WooCommerce Theme (RTL Supported)Armania – Fashion, Furniture, Organic, Food Multipurpose Elementor WooCommerce Theme (RTL Supported)

Cosmetics, medicine, tools, plants, digital, pets, barbers—and loads more! Enter Armania, a WooCommerce Amazon theme with 39+ homepage demos.

Whatever your business, you’re likely to find a demo to match—and if not, you just need to take a look at the huge variety available within the demos to see how you could easily adapt the theme to reflect your business. Take a look at the Kids demo, for example, for a bright and fun version of the Armania theme. 

12. Techmarket – Multi-demo & Electronics Store WooCommerce Theme

Techmarket – Multi-demo & Electronics Store WooCommerce ThemeTechmarket – Multi-demo & Electronics Store WooCommerce ThemeTechmarket – Multi-demo & Electronics Store WooCommerce Theme

With an average of 4.84 stars and 1,800+ sales, Techmarket has its fair share of fans! It’s easy to see why. There are demos for shoe shops, organic markets, glasses stores, gardening centers, sports shops, and last but not least—multi markets that offer a bit of everything. The clean and modern design will help your affiliate products to really shine. 

13. Diassy – Fashion WooCommerce Theme

Diassy – Fashion WooCommerce ThemeDiassy – Fashion WooCommerce ThemeDiassy – Fashion WooCommerce Theme

Enter another simple yet effective WooCommerce Amazon integration, Diassy is your perfect match if you’re in the fashion industry. There are 8 homepage options—each has a different feel, but they all make sure products are front and center.

Homepage 3, for example, has everything an Amazon theme WooCommerce could need—from sliders to display news and offers, to product categories, to Instagram integration. 

14. KuteShop – Fashion, Electronics & Marketplace Elementor WooCommerce Theme (RTL Supported)

KuteShop – Fashion, Electronics & Marketplace Elementor WooCommerce Theme (RTL Supported)KuteShop – Fashion, Electronics & Marketplace Elementor WooCommerce Theme (RTL Supported)KuteShop – Fashion, Electronics & Marketplace Elementor WooCommerce Theme (RTL Supported)

With 6 demos for online markets, one for furniture, one for fashion, and another for sport, KuteShop is ready and waiting to transform your online store! You can also scan the unique QR code from every demo to see how it’ll look on mobile.

The Furniture demo, for example, uses icons to separate product categories for easy navigation. There’s also a useful ‘new arrivals’ content block and a simple newsletter sign-up. 

15. Neoo – Flexible WooCommerce theme

Neoo – Flexible WooCommerce themeNeoo – Flexible WooCommerce themeNeoo – Flexible WooCommerce theme

This simple WooCommerce Amazon theme is modern, sleek, and stylish, With a full-width header, unmissable calls to action, video integration, and a latest news section, it has everything you’d expect from a top WooCommerce Amazon integration. You can also favorite products to come back to them later. 

16. MediaCenter – Electronics Store WooCommerce Theme

MediaCenter – Electronics Store WooCommerce ThemeMediaCenter – Electronics Store WooCommerce ThemeMediaCenter – Electronics Store WooCommerce Theme

And last but not least, MediaCenter is a perfect option if you work with a whole host of Amazon affiliates and have plenty of products to sell. As you can see from the demo, you can include a mega menu with all the different product categories on offer. With an average rating of 4.78 out of 5 stars and more than 2,000 sales, it has plenty of happy customers. 

Your Turn!

As you can see, there’s a huge amount of variety when it comes to WooCommerce Amazon themes. All you need to do is pick the theme(s) that work best for you. Check out Envato Market for the full list of WooCommerce Amazon Affiliates themes. Happy creating!