What Are PHP Arrays?

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on RedditShare on FacebookShare on StumbleUponPin on PinterestShare on LinkedInShare on TumblrBuffer this page

php arrays

Arrays are common not only in PHP, but in any programming language you will come across. Arrays are very useful since they allow us to group together information in a very organized way. At it’s core, an array is a collection of different pieces of information or data which is ordered and indexed via integers. The information gets stored in specific index positions which makes it convenient to insert into and remove out of each pocket or index so to speak. An array can hold pretty much whatever you want to put into it, whether that is a string, number, integer, floating point values, another array, or an object. We’ll be using arrays more and more moving forward so let’s dig right into the nitty gritty with PHP Arrays now!


Creating an Array in PHP

With those beginning thoughts in mind concerning arrays, let’s create one and put some information in it. In this example, let’s imagine we want to have just one variable that contains a collection of house styles. We can do this by creating an array, populating said array with the styles we want, then assigning that array to the variable. This is how we might do this:

Just like that we have an array which is now stored in the $houses variable. Great, so how do we get information out of our array now? Well, lets try to echo out the information in that array like we have been doing with all of the other variable types up until now.

Notice: Array to string conversion in C:\wamp\www\phpconsole\index.php(61) : eval()’d code on line 3
Array

Hmm. Not great. When we tried to echo out the information in our variable, it gave us a warning. It did tell us however that the variable contains an array. There is a different notation for working with arrays when we’d like to retrieve information out of them. We need to specify the index we are interested in using the square brackets notation like so []. You’ll need to keep in mind that arrays are zero based. That means with arrays you don’t begin counting from 1, you count starting at 0. So in our example we populated our array with f different styles of houses. This means we need to look in index [0], [1], [2], and [3]. Notice how we use the square brackets to enclose the index we want to get access to. Let’s try it out in our testing ground:

Colonial
Contemporary
Southwestern
Metro

Nice! Now we’re seeing how to grab the info out of the variable. So at index zero we have our Colonial, index 1 has a Contemporary, index 2 Southwestern, and index 3 has a Metro. With arrays you can store as many values as you need to, maybe you have 500 emails you want to store in a variable, with an array you can do that no problem.

Mixed Values in Arrays

When you have an array, you are not limited to the types that you can store in it. Just above we put a handful of strings into the $houses variable. Now, we can set up variable that is a bit more dynamic. Let’s see how.

7
House
Car

Excellent. First, we assigned a bunch of values to our new dynamic array. At index 0 we placed a number in, specifically an integer. At index 1 is a string. Index 2 is also a string. Note that in the third index is an array. Well how about that America, an array within an array. Yes You Can! Consider this an introduction to multi-dimensional arrays. Having an array within an array requires us to put on our thinking cap. We saw how to get at the data contained in simple array, now how do we deal with this type of thing. Let’s see.

7
House
Car
grass
mower
mulch

Fantastic! When there is an array within an array, you need to level up partner. That is, you need to get to the next level. Notice how we use the double bracket notation to dig deeper into that array within an array [][]. What is this doing for us? Well you see, in the first bracket, we need to specify where we want to look. In this case we want to look at position 3 since that is where the second array lives which we want to peer into. Ok, great – now just repeat the process. Now that you’ve specified the third position of the first array, what position of the second array do you want to access? Put this value in the second bracket. This is how you access arrays inside of arrays and this is what you call a multi dimensional array. You are not limited to only two levels either. You can have arrays within arrays within arrays, however you will begin to drive yourself mad if you nest these things to excess. A good rule of thumb is to try and mimic real data configurations that you might find in the real world. Just for kicks though, let’s put one more array within an array to test it out.

7
House
Car

grass
John Deere
Kubota
New Holland
mulch

Excellent. See how now that there is an array inside an array inside an array, we just use triple bracket notation [][][] to get at that data. Is there really a need to go this many levels deep? Not a lot, but it does help to know how this stuff clicks together, much like our beloved sophisticated interlocking brick system (Legos).

Look Deep Into The Array

When faced with the task of looking deep into the abyss an array, you can make use of the ever useful print_r() function to see how the array is structured. It makes data inside of an array much easier to read. In addition to using the print_r() function, it helps to wrap the output within html pre tags. Let’s see how this works.

Array ( [0] => 7 [1] => House [2] => Car [3] => Array ( [0] => grass [1] => Array ( [0] => John Deere [1] => Kubota [2] => New Holland ) [2] => mulch ) )

Notice here that we use the print_r() function a couple of times. The difference is that the second time, we wrap the output in html pre tags. The pre tags provide a nice formatted output so that it is easier to see how things nest within the array. See how each time we reach another array, the output is indented to give us a visual indication that something interesting is happening here. Put that print_r() function in your back pocket, you’re going to use it all the time when debugging your code. There is one thing to be aware of when retrieving data out of your arrays, and that is you need to specify an index that actually exists or you’ll get an error.

Notice: Undefined offset: 4 in C:\wamp\www\phpconsole\index.php(61) : eval()’d code on line 3

You see we get an undefined offset error if we specify to retrieve data from an index that does not exist. So it seems we’d like to get data out of index 4 but there is nothing there, well let’s add some data into that pocket, it’s easy enough to do, check it out.

Bike

By simply assigning a new value to the variable $dynamic[] using the bracket notation, PHP knows that you want to add something to the end of the array. Note that you didn’t even have to indicate that it was position 4 where you wanted to place something, it just did it for you. Just to bring the idea home, let’s look at one more example.

This is a neat example here. See how we can easily overwrite and existing index by simply assigning a new value to it. This is why index 1 no longer has a House in it, but a Big House in it. Suppose that you need to add something at a specific position, we did that as well. Note that index 9 now has a Surf Board in it.


Associative Arrays

We’re getting a good handle on arrays in PHP, but we’re not done yet. So far we have been working with plain old vanilla index based arrays. The standard index based array relies on numeric keys to work with them. The keys are often invisible to us until we actually output the full array using a pretty print. Associative arrays are a little different in that the keys must be specified explicitly using a label of some type. Think of it like a collection of file folders with labels on them. The label on the folder is the key, while the contents located inside of the folder is the value. The easiest way to see how this works is to simply look at some code.



Nice Work! We have turned our formerly boring standard array into a fully associative array. Now we can access this data using named keys of some type instead of only numeric indices. To be fair, all we did was a pretty print of the contents so let’s look at the actual syntax we would need to use to access all of this information.

7
House
Car
grass
John Deere
Kubota
New Holland
mulch

Slick! See how instead of putting the number of the index in between the brackets, we now put in the label, whatever that may be. Note that for arrays within arrays, you might need to use a combination of index based and associative labels to get at the data you are looking for just like we did above.

Wrapping Up

We have the basics of PHP arrays covered. Use this and other examples to refine your skills. Soon we will dig into all of the amazing functions for dealing with arrays that PHP provides to us, and there are many!

Thank you for reading What Are PHP Arrays?Please do share using the buttons below!

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on RedditShare on FacebookShare on StumbleUponPin on PinterestShare on LinkedInShare on TumblrBuffer this page

11 Fun Hacks to Get Your PHP Integers and Floating Point Values Mastered

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on RedditShare on FacebookShare on StumbleUponPin on PinterestShare on LinkedInShare on TumblrBuffer this page

PHP Integers and Floating Point Values

We’ve covered a ton of information about strings in PHP and their associated string functions, now we’ll take a look at working with numbers in PHP. Numbers are important. If you think about it, we deal with numbers and math all day, every day. It helps to be good with numbers for calculating your budget, picking statistical favorites in your office fantasy league football team, investing based on numerical data, and oodles of other scenarios. In PHP just like all other programming languages we’ll typically be dealing with whole numbers and decimal based numbers. In programming parlance we’d be referring to integers and floating point numbers respectively. It’s a fairly straightforward topic and can be fun as well, so let’s jump right in to integers and floating point numbers in PHP!


Integers in PHP

When we think of integers, we’re talking about whole numbers. 1, 2, 3, 4, 5 and so on. Integers can also have negative values, so going in the reverse direction is also valid. -1, -2, -3, and so on are all integers as well. We can do simple math with integers and everything works just like it does in Algebra. All of the orders of operation and operator precedence hold true. Parenthesis can be used to assign priority to orders of operation. Check out this example:

15

As we can see, by following the standard math rules we come up with the answer of 15.

PHP Math Functions

PHP has several math functions that are quite useful, let’s have a look at a few of them.

Random Min Max – 7
Random – 9524
Modulo – 6
Square Root – 8.6602540378444
Exponential – 256
Absolute Value – 250

These functions work just like we would expect according to the standard math rules. Going through the examples, first up is the Random number generation with a minimum and maximum values. Here we provide a minimum of 1 and a maximum of 50. Each time you run this snippet, you’ll get a random whole number between 1 and 50. You can also run this particular function without providing a min or max value. The modulo takes two numbers and divides them. It returns the remainder of that calculation. The square root function calculates the square root of the number you provide to it. Exponential takes two numbers, the number, and the exponent to assign the power of. Lastly in this group of examples is the absolute value. This gives back the absolute value of the expression within it. For example, if the result comes out to a negative value, the absolute value will give you the actual value without the negative.

Increment and Decrement Numbers in PHP

When working in programming, we often need to add to or remove values from a variable during the course of a script executing. There are a few ways to do this. First we’ll look at incrementing a number.

Increment

10
10

These two examples do the same thing, however you can see their syntax is slightly different. The first example takes the number, then it says assign this number plus 5 and provide this to us. In the second example we use the plus equals shorthand notation. Note that it works the same exact way and gives us the same result, but it is easier and faster to type. This works just the same with multiplication, subtraction, and division. Don’t believe it?! Check it out:

0
0
25
25
1
1

Very Cool!

With the approach we were using above, we were dealing with incrementing and decrementing by using the number 5. We can do this with any value that the problem to solve may call for. A very common use case however is simply adding or subtracting one to a number. This is so because when you work with loops in PHP, adding or subtracting 1 to the iterator happens all the time. Let’s see how to do this.

Post Increment or Decrement

This is the most common way to deal with adding or subtracting a value. Have a look at this:

7
7

Hey Wait! Those numbers are the same as when we started! This is because we are doing post increment and decrement. You see what happens here is PHP echos out the value first, then increments the variable. If we change up the code just a little, we can see how this works.

8
6

That’s more like it. In this snippet we make use of a second variable, $result. So the flow looks like, assign 7 to $number, assign $number to $result then increment $number, echo out $number. It’s a little tricky but will become second nature to you after a while.

Pre Increment or Decrement

You’ll notice that in making use of the Pre Increment or Decrement, the ++ or -- goes before the variable, not after. It’s a subtle yet important difference. You can see that when we echo out the value of the variable, the updated value is produced straight away. How is this? Well in this case, PHP assigns 7 to $number, it then increments $number by one, and finally produces the value to the screen. The same flow happens with the decrement, and this is why the output is 8 and 6.

8
6

Strings Are Not Numbers

Strings are not numbers and numbers are not strings. Well this would seem painfully obvious, yet it is easy to get tripped up with PHP since it does type conversion on the fly. Consider this snippet:

not equal
2

Verrrrry Interesting… In the first if statement we say if the first variable is not equal to the second variable, then echo out not equal. This is exactly what happens when the code runs. Note however that we then echo out variable 1, an integer, plus variable two, a string, and we get the number 2. This should seem very strange to you if you’re new to programming. The number 1 plus the letter one can not possibly be 2! What happens with this is that PHP inspects the second variable and does its best to assume what is meant by the string 1 in terms of a numerical value since we are trying to complete a math operation. This is interesting how this type juggling works but you should really make sure you know what types you are dealing with and explicitly set and convert them as needed when programming. Don’t rely on PHP to do it for you lest you find yourself in a world of hurt when you can figure out why things are not working.


Floating Point Numbers in PHP

This brings us to another type of number in PHP, the floating point. So what does this mean? Do these numbers magically float among the clouds? Are they like a balloon filled with helium? No, no they don’t do anything fun like that. Floating point is just a fancy way of saying a number that has decimal places. We use floating points everyday in our lives. Want to buy a coffee? Sure, that’ll be 2.47 please. There you go, you just made a floating point transaction with your friendly Barista. See that, easy as pie.

Why Floating Point?

It may seem odd that with computers we need to have two types of numbers. In the real world, we simply have numbers, and we deal with them accordingly. It turns out computers compute and store numbers differently. Computers store integers and floating points in different ways. Here are a few examples of some floats:

7.12
12.12
1.6666666666667

You see we can assign a float to a variable, add a number to a float, or divide a number which returns a floating point value.

Floating Point Functions

Sometimes it will be useful to apply any of the built in PHP functions for floats. We have functions like round, ceil, and floor to do just that. Mainly, these are just simple rounding functions and they do what their name appears as. This snippet gives you an example of how these work:

7.1
8
7

Is that a Float in your Pocket?

Is that a float in your pocket or are you just happy to see me? Many times you’ll need to check a variable to see if it is a float or an integer. You might also need to simply check to see if it is a numeric value. There are a few easy ways to do this, let’s see how.

Is 5 an integer? Yep!
Is 7.12 an integer? Nope!
Is 5 a float? Nope!
Is 7.12 a float? Yep!
Is 5 a number? Yep!
Is 7.12 a number? Yep!

The 11 Fun Hacks to Get Your PHP Integers and Floating Point Values Mastered Summary

We covered the beginnings of Integers, Floating Points, and Numeric Values in this action packed episode of learning PHP fundamentals. So far we’ve take a look at the history of PHP, how to work with strings, we covered PHP string functions soup to nuts, and now we’ve got your numbers covered. Stay tuned for even more random bits of awesomeness about PHP to come in the following episodes.

Thank you for reading 11 Fun Hacks to Get Your PHP Integers and Floating Point Values MasteredPlease do share using the buttons below!

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on RedditShare on FacebookShare on StumbleUponPin on PinterestShare on LinkedInShare on TumblrBuffer this page