Tag Archives: Foreach

PHP: Arrays or Linked Lists?

Arrays vs. Linked List

If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks.

Array & Linked List
Array & Linked List

The items of a linked list keep a reference to their successor, so we can easily walk through the entire list. However we don’t have direct access to its elements. Thus we can’t go directly to its middle element! Even more – in particular implementations of a linked list we don’t know its length. But in some cases linked lists are far more effective than arrays. For instance reversing an array of non-numeric values require constant additional memory, but also requires n/2 exchanges. The same taks using linked lists is not only performed in linear time, but doesn’t require any additional memory. The only thing we need to do is to reverse the links – no movement of values and the items remain at the same place in the memory.

Merging of two arrays often require more space (proportional of the space of the two arrays) or many exchanges in case we try to do it in place. The same task on linked lists is far more effective with only changing pointers and without moving the values. Continue reading PHP: Arrays or Linked Lists?

Thing to Know About PHP Arrays

Consider the following case. We have an array with identical keys.

$arr = array(1 => 10, 1 => 11);

What happens when the interpreter reaches this line of code? This is not a syntax error and it is completely valid. Very similar, but more interesting case is when we have an array of identical keys, where those identical keys are represented once as an integer and then as a string.

Keys in PHP arrays are not type sensitive, so pay attention when using them!
Keys in PHP arrays are not type sensitive, so pay attention when using them!

$arr = array(1 => 10, "1" => 11);

Now several questions arise. First of all, how many elements have this array? Two or one. This can be easily verified by checking what count() will return. Continue reading Thing to Know About PHP Arrays

PHP: Fetch $_GET as String with http_build_query()

PHP is really full of functions for everything! Most of the time when you try to do something with strings, there’s a function that can do it better and faster.

The Route from $_GET to String

The global arrays in PHP contain request parameters. Either GET or POST. As you know if the page address is something like:

http://www.example.com/index.php?a=b&key=value

This means that you pass to the index.php file two parameters – “a” and “key” with their values: “b” and “value”. Now in this case you can dump the $_GET global array somewhere in index.php and you’ll receive something like this.

array(
	"a"   => "b",
	"key" => "value",
);

This is however pseudocode, but in fact $_GET will be very similar to this sample array. Continue reading PHP: Fetch $_GET as String with http_build_query()

Using PHP’s array_diff in Algorithm Development

array_diff can be really powerful. Once you’ve to find the different elements between two arrays you’ve to use array_diff. Here’s a case when you can use it while coding a simple algorithm.

The Task

You’ve one array with tickets of linked destinations – so you start from one city to another, than next and so on. Each element is an array with “from” and “to” destinations:

$inputTickets = array(
    0 => array('from' => 'barcelona', 'to' => 'madrid'),
    1 => array('from' => 'sofia', 'to' => 'paris'),
    2 => array('from' => 'madrid', 'to' => 'milano'),
    3 => array('from' => 'paris', 'to' => 'barcelona'),
    4 => array('from' => 'cupertino', 'to' => 'sofia'),
    5 => array('from' => 'milano', 'to' => 'valencia'),
    6 => array('from' => 'valencia', 'to' => 'nice'),
    7 => array('from' => 'mountain view', 'to' => 'cupertino'),
);

It’s easy to construct two arrays – the “from” destinations array and the “to” destinations array, and here the easiest way to get the starting point of the whole trip, because of the fact that these are linked tickets.

$fromDestinations = $toDestinations = array();
 
foreach ($inputTickets as $k => $v) {
    $fromDestinations[] = $v['from'];
    $toDestinations[]   = $v['to'];
}
 
// and finally get the starting point
$startPoint = array_diff($fromDestinations, $toDestinations);

Conclusion

Beside of knowing several algorithm techniques, there’s also need of knowing the language syntax and possibilities – in that case PHP’s

One Form – Multiple DB Records

I’ve the impression that even it’s a simple technique it remains quite misunderstood!

What’s the Goal?

You’ve a simple HTML form with several groups of form elements. Imagine the situation with title and link groups. You can have 1, 2 or more title/link pairs which you’d like to save in a database table, where perhaps there are only three columns – id, title, link.

What is the Shortest Path to the Solution?

In fact the task can be done by many ways, but there’s one really elegant solution. As it appears in many occasions PHP and HTML are born to work together!

1. First Step

Create your web form by simply modifying a bit the element names. Usually when you have an input you simply name it after the database column or something similar.

<form method="POST">
	<input type="text" name="db_column_name" />
</form>

In reality PHP and HTML allows the name to be an array element, just like so:

<form method="POST">
	<input type="text" name="link[0][title]" />
	<input type="text" name="link[0][url]" />
 
	<input type="text" name="link[1][title]" />
	<input type="text" name="link[1][url]" />
</form>

2. Second Step

Than all this comes in the _POST array in PHP, but formatted in an array manner, so you can simply foreach it!

<?php
 
foreach ($_POST['link'] as $link) {
	insert_into_db($link['title'], $link['url']);
}
 
?>

That is simply enough!