Composite variable in PHP (Arrays, Object and more)

Coding (Php 7.x)

Jan 4, 2019

Learn the secrets of PHP composite variables such as arrays objects, resources and null
 
/img/blog/composite-variable-in-php.jpg

Introduction

 

So,

 

In the previous episodes of this series, you learned what the scalar variables are.

 

Strings, integers, booleans, etc. They are the basics of any programming language.

 

Now it's time to introduce the variables of a composite type.

 

This type of variables is a bit more complex to grasp, but after understanding the concept you will not have any problems to fully exploiting their power in your scripts.

 

As you will see,

 

this type of variable is nothing more than a set of scalar variables combined into a single group.

 

There are two types of variables that belong to this group and are: Arrays and Objects,

 

Also,

in order to complete the variable section, you will now see two other types of variables that are Resources and Nulls.

 

As you saw a composite variable is nothing but a set of scalar variables,

this is useful when we want to group and work on many elements of the same type,

 

Think about the list of the names of your classmates, say that you had (or still have) 20 of them.

It will not be very performing, not to mention the difficulty in managing 20 different string variables, much more simple will be to create a single variable, an array in this case, and insert all 20 names inside.

 

Think now about all the information in your ID card,


Name, surname, address, age, height.

 

All information types vary from strings to integers to floats that affect a unique object (in this case an individual or person).

 

In this episode, you will learn how to exploit these composite variables and create better programs with less stress and more fun.

 

 

 

PHP Basics for Expert Developers

 

This blog post is part of a series called "PHP Basics for Expert Developers".

 

In this series, you are going to learn the basics of PHP but you will also see many small tips and features that you will only find in books and advanced tutorials.

 

Depending on your level you may simply want to read them sporadically or skip them altogether.

 

You do not have to learn all that is written here by heart!

 

Simply read, find out that certain features or techniques exist and return to these pages when you feel ready for the next level.

PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

 

Also this blog post is divided in 4 main sections

Arrays variables
Objects variables
Resources variables
Null variables

 

Let's Start!

 

 

Array variables


Arrays are ordered maps that associate values with keys,

 

There are three different types of arrays, they are indexed, associative, and multi-purpose.

 

PHP provides about eighty functions that have the most disparate uses, so before creating operations on arrays on your own you should look for something ready to use.

 

In PHP 7 it is possible to declare arrays in two different ways,

with short syntax and long syntax
 

$automobile = ['Mercedes', 'Ford', 'Alfa'];
$automobile = array('Mercedes', 'Ford', 'Alfa');

 

Even if you used different syntax the two arrays just created above are exactly the same.

 

Having specified only the values but not the keys coupled to them PHP automatically indexes each value with an increasing number starting from 0,

which means that if we want to get the value "Ford" from the previous array we must indicate an index of 1.

 

To retrieve the values within an array we must indicate the index or key using square brackets.
 

echo $automobile[1];
// Ford

 

Let's see another example:

$motorbike = [
    'Manufacturer' => 'Ducati', 
    'Model' => '999',
    'Class' => 'Sport'
];

 

In this case, we are pointing to the keys inside the array,

this is called an associative array and to retrieve the values of this array we need to use the specified keys.

 

echo $motorbike['Model'];
// 999

 

There is no need to specify all the array values at once you can add values even after the array has been created using the '=' assignment command.
 

$motorbike['Transmission'] = '6-speed';

 

Consider that it is also possible to create numbers and keys in the same array.

 

$array = [0 => 'id', 'name' => 'John', 'surname' => 'Doe'];
$array[] = 2018;

print_r ($array);
Array (
    [0] => 'id',
    ['name'] => 'John',
    ['surname'] => 'Doe',
    [1] => 2018
);

 

 

Note that,

 

PHP automatically gave the index of 1 to the new value.

 

Until now you have seen that we have added scalar type variables as values within arrays,

 

but,

PHP also gives you the possibility to add arrays inside arrays,

 

The result of it is called a matrix.

 

$menu = [
     'cappuccino' => [
         'espresso', 'steamed milk', 'milk foam'
     ],
     'macchiato' => [
         'espresso', 'steamed milk'
     ],
     'americano' => [
         'espresso', 'hot water', 'more hot water'
     ]
];

To get the third ingredient of a cappuccino this is the command to use:

$Menu[cappuccino][2];
// milk foam

 

The first index refers to the first level of the $menu array the second refers to the index inside the array with the indicated key,

in this case, "cappuccino",

Remember that arrays work at 0 basis which means that to retrieve the third value you have to specify index 2.

 

You can find some other example in this tutorial written by Topher DeRosia.

 

I am planning to create a series of blog posts that are going to describe in details all the array functions available in PHP 7.1,

 

To get notified when they will be published subscribe to my newsletter and get free reviews of the best books for PHP developer.

 

 

Objects variables

 

In Object-Oriented programming, an object is an instance of a class

It is a unique element, separated from other objects with which it can communicate.

 

To define an object it is necessary to identify its characteristics also called attributes and the actions that the object can perform commonly called methods.

 

An instance is a given object of a given class, every instance is separated from the others but shares its general characteristics with the other objects of the same class.

 

Continuing to use the example previously used for arrays we can say that a car created by Ford and a car created by Mercedes are two different objects

 

but,

at the same time,

 

both can be instantiated by the automobile class,

both elements of the automobile class have a steering wheel and an engine,

but these attributes differ from one each other.

 

 

As said,

All the objects of the automobile class have an engine but each object has a different engine size (cc) and a different power.

 

These concepts and others such as encapsulation and polymorphism must be best described on an in-depth object-oriented programming tutorial.

 

Technically speaking, in object-oriented programming, an instance of a program is the representation in RAM memory of the class to which the object corresponds

 

I will not dwell further on objects and Object-Oriented programming as I have already published a whole series of blog posts called "The complete guide to OOP" on my website see the link below for more details.

 

 

 

Resources variables

 

A resource is a special type of variable.

 

These variables hold a reference to an external resource,

these resources are created and used by special functions that PHP language provides.

 

Currently in PHP 7.3 there are about 103 special functions ranging from the creation of PDF to the creation and parsing of XML, functions that manage the Socket, the stream, printers, Open SSL, MySQL and many others.

 

Here is a list of all the resources types available in PHP

 

To check that a variable is a resource type, use the function is_resource() which returns a variable of type bool (thus true or false).

 

Another very important function when working with resources is get_resource_type() that instead returns a string indicating the type of resource.

 

A resource contains references to open and manage files, database connection, and so on.

 

The PHP engine is able to terminate when a resource has no more references and deletes it, which means that it is not necessary to free up memory manually.

 

Obviously, links from persistent databases connections are an exception to this rule and therefore must be managed accordingly

 

 

NULL 

Null is a type of special variable.

 

The only possible value for a null variable is NULL.

 

There are three ways to create a null variable:

the first and assigning the constant NULL to the variable,

the second and using the unset () function on a variable

the third occurs when the variable has not been set yet.

 

This type of variable has only one value which is the case-insensitive null value.

 

Also,

from PHP 7.2 it is not possible to do casting on null variables.

 

There are two main functions that work on NULL variables.

 

The first is the function is_null() which returns a boolean value if the variable indicated as parameter is NULL,

 

the second function is unset() which takes a variable of any other type and makes it NULL.

 

Null variables indicate the absence of a value rather than indicating the value itself.

 

Consider this type of variables as an empty slot in memory or missing information.

 

That's why null variables are considered unset.

 

They do not have a value,

 

in fact, the variable remains only so that you can give a value to it, after in your code, this is very important because the variable in question can be an element of an array or a property of an object.

 

If you want more details here is Null described on the official manuals.

 

 

 

Conclusion

 

Here we are,

 

This was a short, keep-it-simple episode,

 

But what you have just learned is going to serve you over the years if not decades of programming before you.

 

I know, 

you're now wondering how to implement this new knowledge in your code,

 

what you can do with them and why use them in the first place.

 

If this is the first time you see composite variables you are also wondering why you should complicate your life and why not just use scalars instead.

 

Here is a tip.

 

Practice creating them, understand what is the difference between an array and an object.

When you need to create one when you need to create the other.

 

The next step will be to learn how to use these variables (scalars and composite) in your code.

 

Use them inside control structures or inside loops.

A tutorial in this will be published soon so stay tuned!.

 

Once done,

there are about a hundred functions that PHP 7 makes available to edit, create, modify all the variable you wish.

 

We are not quite there yet.

 

Keep practicing,

Do not stress out, enjoy the learning process

 

PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

 

-----

 

Now you know the basis, it is time to start practicing,

 

Take advantage of the power and the speed of Blue Host and create an account where you can exercise and see your improvement on a live server at less than a Starbuck's Caffe Mocha per month.

(This is an affiliate link, The price stays the same for you and it helps me improve this content.)

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Dec 26, 2018

How to use variables (PHP 7)

Get the ebook See details
Coding (Php 7.x) Jan 7, 2019

PHP operators (part 1)

Get the extra See details
Coding (Php 7.x) Jan 11, 2019

PHP Operators (part 2)

Get full article See details
Get my free books' review to improve your skill now!
I don't want to improve