Home     Wordpress     Codex

Posts Tagged ‘array’

Learning PHP (5) – Using built-in functions

June 12th, 2009 by admin | No Comments | Filed in Learning PHP

I had promised myself that I would post every second day, but I didn’t know exactly where to go from what we have built up and I also became engaged, she said yes! So it has been crazy days.
But I’m happy, at least :-D

I am going to continue with showing how to take use of some of the built-in string fuctions. These can be used to manipulate text variables that you might receive from the $_GET and $_POST variables.

Find occurrence of text in strings
You can for example use the function strstr() or stristr() if you want a cast-insensitive matching style.

Example

$mystring = 'this websites owner is nice';
if (strstr($mystring, 'website')) {
 echo 'I found the word "website" in the string.';
}

I can use double quotes in the string because I have it enclosed in single quotes.
If I were to use single quotes it would unquote the string and generate a syntax error.

If you replace strstr with stristr in the example, it would
also give a match if $mystring contains the word ‘Website’ with an upper case W.

explode() strings
If you get a string such as “one,two,three,four,five,six” and you would rather have
it indexed in an array you can use the function explode() to achieve this.

The build-in function explode() will parse a string and split it based on the
argument you give the function. An example will follow:

$mystring = "one,two,three,four;five,six,seven";
$myarray = explode(",", $mystring);

var_dump($myarray);

The first argument to explode is the delimiting character, while the other
is the string that will be split into an array. The result of this would be:

array(6) {
[0]=>
string(3) “one”
[1]=>
string(3) “two”
[2]=>
string(5) “three”
[3]=>
string(9) “four;five”
[4]=>
string(3) “six”
[5]=>
string(5) “seven”
}

Notice that $myarray[3] contains four;five, this is due to a common
mistake.. it can be hard to overlook, so can you figure out why it does that? :-D

Anyways, you should check out the documentation and try out some
of the functions, because they are really easy to use and implement.

Good luck!

Tags: , , , , , , , ,

Learning PHP (3); Reserved vars and loops

May 28th, 2009 by admin | 1 Comment | Filed in Learning PHP

In my previous article I explained arrays and their use. But have you ever wondered what happens to those variables set in the url? They are contained within an array which is prefilled for your scripts.

The array variables $_GET, $_POST and $_SERVER are some of the interesting ones you can use.

The reserved $_GET variable
An example would be this type of URL.
http://www.example.domain/myphpscript.php?name=Espen

To catch the variable ‘name’ you can do this piece of PHP

<?php
echo “Hi ” . $_GET['name'];
?>

This will output “Hi Espen”.

Using the reserved $_POST variable
To get the variables from a form you can use $_POST['key'].
Look at this example:

Create this HTML form, change the path to myhelloscript.php to a place where you test your scripts.

<form action=”http://my.domain/myhelloscript.php” method=”post”>
<input type=”text” name=”name”>
<input type=”submit” value=”send it”>
</form>

Then create the file myhelloscript.php with the following contents

<?php
echo “hi ” . $_POST['name'];
?>

You see? The same result here, only now we’re using POST instead of GET (you can also notice that the URL does not contain the variables).

Looping over an array
Looping over an array can be very usefull in the case where you don’t know what the reference keys are.
Let us say you didn’t know that the key for the name in the previous post example was not called  ‘name’, how would you find it?

Here is an example of looping over an array, looping through all the key and value pairs.

<?php
$myarray = array(‘Espen’, ‘John’, ‘Lisa’, ‘Mark’);

foreach ($myarray as $value) {
echo $value . “<br>”;
}
?>

Now we’re saying for each ‘entry’ in $myarray get the entry as $value and do something with it between the { and }
So for each $myarray as $value: echo $value and a ‘<br>’ (to get a newline).

This example will output

Espen
John
Lisa
Mark

Getting the key
But that’s not the key, is it?  How do you find the keys?
This example will use the foreach command in another way to get the keys also

<?php
foreach ($myarray as $key => $value) {
echo $key . ‘ is ‘ . $value . ‘<br>’;
}
?>

Now you can also use the variable $key within the loop for each value to get the corresponding key.

This is an example of looping over the $_GET array

<?php
foreach ($_GET as $key => $value) {
echo $key . ‘ is set to ‘ . $value . ‘<br>’;
}
?>

A Challenge
The $_SERVER variable contains a lot of variables about the request, can you figure out how to show them all?

If you get any weird syntax errors or such, post them as a comment and I will try to help you out!

Tags: , , , , ,

Learning PHP – Part two; Arrays

May 26th, 2009 by admin | 1 Comment | Filed in Learning PHP

Here’s my follow up on my PHP articles, this time I am going to talk a bit about arrays. They are so important that you should learn about them sooner than later.

What are arrays?
This quote is from wikipedia.org

An array is a systematic arrangement of objects, usually in rows and columns. Specifically, it may refer to several things.

That’s exactly what it is, it’s a variable (see previous post) containing several values (like a shelf with several compartments) that can be retrieved by a key (the number on the compartment). Array keys are per default a number, but it can also be an associative array with text strings for keys.

So make an array and fill it with data
Here is an example on how to declare an array:

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);
?>

The variable name is $bookshelf, it is set to be an array(). The contents is put in between the (), but you can also declare an empty array by doing this:

$bookshelf = array();

By default, the first value will have the key 0, the second will have 1, etc.
To refer to a value within an array and echo it out to display:

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

echo $bookshelf[0];

?>

The result outputted from this script will be:

old books

By using the [ and ] signs behind a variable you are referring to it as an array, what you put between them is the key you are using. Try to change the value between them to 1 and check the result.

Adding values to a PHP array
You can make use of the array_push() function to insert more variables to a previously declared array.

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

array_push($bookshelf, ‘dvds’);

echo $bookshelf[3];

?>

You can also set a variable directly by using the key

<?php
$bookshelf = array(
‘old books’,
‘new books’,
‘cooking books’
);

$bookshelf[3] = ‘dvds’;

echo $bookshelf[3];

?>

Deleting a value from a PHP array
Several ways to this also, you can use array_pop() to unset the last value in the array.
The unset() function can be on the array value to unset it.
You can set it to null by referring to the key

array_pop($bookshelf);
unset($bookshelf[3]);
$bookshelf[3] = null;

While these are regular arrays, there are other possible ways to use this. A string variable like $name = “Espen”; in my previous article is actually an array of characters. $name[0] will refer to ‘E’, 1 will refer to ’s’ so on and so forth.

Associative Arrays in PHP
You can use keys which are not numbers in an array, those are called associative arrays.
Here is an example, I bet you understand most of the basics now, and in case NOT – drop me a comment!

$bookshelf['favourite'] = ‘Marketing 911′;
echo $bookshelf['favourite'];

In my next article you will get magic behind the array variables $_GET, $_POST and $_SERVER to finally be able to handle user input from forms and every secret of the request. Want to know when I post it? Get Learning by RSS.

Tags: , ,