<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gadratil Programming &#187; php</title>
	<atom:link href="https://www.gadratilprogramming.net/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.gadratilprogramming.net</link>
	<description>Re-imagine the small things</description>
	<lastBuildDate>Fri, 13 Mar 2026 16:50:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Handling tree structures in PHP</title>
		<link>https://www.gadratilprogramming.net/handling-tree-structures-in-php/</link>
		<comments>https://www.gadratilprogramming.net/handling-tree-structures-in-php/#comments</comments>
		<pubDate>Mon, 13 Jun 2016 12:27:38 +0000</pubDate>
		<dc:creator><![CDATA[Gadratil]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[infinity]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[recursivity]]></category>
		<category><![CDATA[root]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[storage]]></category>
		<category><![CDATA[tree]]></category>

		<guid isPermaLink="false">http://www.gadratilprogramming.net/?p=252</guid>
		<description><![CDATA[What is a tree? A tree is a scructure of data used for categories, showing hierarchy and so on. In web applications usually the most used case is creating category hierarchy, menu hierarchy or page hierarchy. Currently there are a lot of ways to create tree scructures in PHP, but we will use just one [&#8230;]]]></description>
				<content:encoded><![CDATA[<h3>What is a tree?</h3>
<p>A tree is a scructure of data used for categories, showing hierarchy and so on. In web applications usually the most used case is creating category hierarchy, menu hierarchy or page hierarchy. Currently there are a lot of ways to create tree scructures in PHP, but we will use just one example, one that is very flexible and adaptable for many usecases.</p>
<h3>Example of a tree</h3>
<p>For the sake of simplicity, we will use a very simple tree for example. Our tree looks like this:</p>
<p><a href="http://www.gadratilprogramming.net/wp-content/uploads/2016/06/Untitled-Diagram.png"><img class="aligncenter size-full wp-image-254" src="http://www.gadratilprogramming.net/wp-content/uploads/2016/06/Untitled-Diagram.png" alt="Tree" width="153" height="303" /></a>This is a one depth tree with four nodes in total. In trees, the nodes that have children are called branches and the ones that have none are called leaves.</p>
<h3>How to store a tree</h3>
<p>When working with simple trees, storing the hierarchy is not that hard. Usually, in the database we can create a parent column that contains the parent of a given node. In tree structures, every node can have only one parent, the only exception being the root. The root node has no parent.</p>
<p>Now, if we know how deep our tree will be, using just the parent for information, we are set. If we do not know the depth exactly, things are a bit more complicated. Since people created databases, a lot of storing methods have been born that help store recursive data linearly. Each is different in a way and each is good at something, but bad at other.</p>
<p>Our example is a basic linear representation and is pretty quick. It contains some extra info that some might consider an overhead, but it is simple, logical, and it works.</p>
<table class="table" style="background-color: #b8f5e3;" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Parent</th>
<th>Tree</th>
<th>Slug</th>
<th>Name</th>
<th>Path</th>
<th>Children</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>NULL</td>
<td>1</td>
<td>root</td>
<td>Root</td>
<td></td>
<td>|2,3|</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
<td>node1</td>
<td>Node1</td>
<td>|1|</td>
<td>|4,5|</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
<td>nod2</td>
<td>Node2</td>
<td>|1|</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>1</td>
<td>child1</td>
<td>Child1</td>
<td>|1-2|</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>1</td>
<td>child2</td>
<td>Child2</td>
<td>|1-2|</td>
<td></td>
</tr>
</tbody>
</table>
<p>This is how we store the data. Every row is a node. The columns are as following:</p>
<p><strong>Id:</strong> this is the autoincrement unique id of every node.</p>
<p><strong>Parent:</strong> This contains one integer, the Id of the parent node. This is mainly formality and is used in simple cases.</p>
<p><strong>Tree:</strong> with this field, we can have more than one tree in one table. This is an integer and is the id of the tree we work with. Every tree has a root node that is mandatory</p>
<p><strong>Slug:</strong> this is a slug, created from the given name and is always unique in the table. This is an additional unique field besides the Id.</p>
<p><strong>Name:</strong> this is the name of the node.</p>
<p><strong>Path:</strong> this column coontains the ids of the nodes that are before our node on the branch from the root, merged into a string. This contains the full path from the root till the node. This is handy in building the hierarchy in PHP.</p>
<p><strong>Children:</strong> contains all the ids of the children of a node, merged into a string. This also stores the order of the children.</p>
<h3>Handling tree in PHP</h3>
<p>In PHP, we can easily manipulate this data. We will have some basic examples to show the perks of this type of DB structure.</p>
<p>For start, how do you get the tree? With one simple query, we can get the whole tree, or just a subtree, using the id of the root node. The nodes that have paths that contain the given id, all belong to the same subtree. This looks like this:</p><pre class="crayon-plain-tag">SELECT * FROM `table_name` WHERE 
			`path` LIKE "%-:parent-%"
			OR `path` LIKE "%|:parent-%"
			OR `path` LIKE "%-:parent|%"
			OR `path` LIKE "%|:parent|%"</pre><p>When we have the data, we have to convert the strings into actual PHP arrays for us to be able to easily use them later. We do this like:</p><pre class="crayon-plain-tag">$node-&gt;path = array_filter(explode('-', str_replace('|', '', $node-&gt;path)));
$node-&gt;children = array_filter(explode(',', str_replace('|', '', $node-&gt;children)));

$node-&gt;path = array_filter(explode('-', str_replace('|', '', $node-&gt;path)));
$node-&gt;children = array_filter(explode(',', str_replace('|', '', $node-&gt;children)));</pre><p>One other important aspect is moving the nodes from a parent to another, being able to move the whole subtree if necessary. In our case this is not hard, we just have to update some strings. In PHP this means slicing and rearranging our arrays of children and path. Something like this:</p><pre class="crayon-plain-tag">// Get old parent
$old_parent = $this-&gt;getNode($node-&gt;parent);
			
$old_parent-&gt;children = array_diff($old_parent-&gt;children, array($node-&gt;id));
$this-&gt;_storage-&gt;begin_transaction();
			
try
{
	$this-&gt;_storage-&gt;updateNode($old_parent);
				
	$arr2 = array_slice($to-&gt;children, $order-1);
	$arr1 = array_diff($to-&gt;children, $arr2);
	$to-&gt;children = array_merge($arr1, array($node-&gt;id), $arr2);
				
	$this-&gt;_storage-&gt;updateNode($to);
				
	$node-&gt;parent = $to-&gt;id;
	$node-&gt;path = array_merge($to-&gt;path, array($to-&gt;id));
	$this-&gt;_storage-&gt;updateNode($node);
				
	foreach( $subtree as $subnode )
	{
		$subnode-&gt;path = array_merge(
			$to-&gt;path,
			array($to-&gt;id, $node-&gt;id),
			array_diff($subnode-&gt;path, array_merge($node-&gt;path, array($node-&gt;id)))
		);
					
		$this-&gt;_storage-&gt;updateNode($subnode);
	}
				
	$this-&gt;_storage-&gt;commit_transaction();
				
	return true;
}
catch(Exception $e)
{
	$this-&gt;_storage-&gt;rollback_transaction();
	$this-&gt;_errors['move'] = $e-&gt;getMessage();
	return false;
}</pre><p>Ordering is also easy. Ordering is done on a given level, so we use the children column to order the nodes. The code would look like this:</p><pre class="crayon-plain-tag">$children = array_diff($to-&gt;children, array($node-&gt;id));
$arr2 = array_slice($children, $order-1);
$arr1 = array_diff($children, $arr2);
$to-&gt;children = array_merge($arr1, array($node-&gt;id), $arr2);
			
$this-&gt;_storage-&gt;updateNode($to);</pre><p>Upon deletion, using the move section, you can prompt the user to move the subtree to root, or delete the whole subtree.</p>
<p>Using LIKE syntax in SQL, you can achieve a lot of things.</p>
<p>One last thing that needs mentioning is the recursive function that builds the N depth out of linear data we just got from DB. Here it is:</p><pre class="crayon-plain-tag">private function _build_tree(Node $root, $data)
{
	$mapped_node = array(
		'node' =&gt; $root,
		'subnodes' =&gt; array()
	);
		
	if ( !empty($root-&gt;children) )
	{
		foreach( $root-&gt;children as $child )
		{
			if ( array_key_exists($child, $data) )
			{
				$mapped_node['subnodes'][] = $this-&gt;_build_tree($data[$child], $data);
			}
		}
	}
		
	return $mapped_node;
}</pre><p></p>
<h3>Conclusion</h3>
<p>You can find all these pieces of code in the <a href="https://gitlab.com/Gadratil/PHPInfinityTree" target="_blank">PHPInfinityTree</a> repository on GitLab. This is probably not the best solution, but is simple, understandable and is quick. Since recursivity cannot be used in many databases, we have to store the data linearly. Then we go trough it linearly and build up the tree itself.</p>
<p>You can find a working example on <a href="http://infinitytree.gadratilprogramming.net" target="_blank">PHPInfinityTree.</a></p>
<p>Also, you can find the packed and documented package of <a href="http://www.gadratilprogramming.net/shop/php-libraries/php-infinity-tree/" target="_blank">Infinity Tree in the Store</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.gadratilprogramming.net/handling-tree-structures-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to structure a basic PHP file</title>
		<link>https://www.gadratilprogramming.net/how-to-structure-a-basic-php-file/</link>
		<comments>https://www.gadratilprogramming.net/how-to-structure-a-basic-php-file/#comments</comments>
		<pubDate>Thu, 02 Jun 2016 12:48:20 +0000</pubDate>
		<dc:creator><![CDATA[Gadratil]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code structure]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[readability]]></category>

		<guid isPermaLink="false">http://www.gadratilprogramming.net/?p=243</guid>
		<description><![CDATA[When creating code, PHP gives us a huge freedom. Since PHP is compiled at runtime, it can be mixed with any text inside the file. Then, when the code is compiled, the content of the file gets to the output (usually your browser). If you create a small project, using this technique is totally ok. [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>When creating code, PHP gives us a huge freedom. Since PHP is compiled at runtime, it can be mixed with any text inside the file. Then, when the code is compiled, the content of the file gets to the output (usually your browser).</p>
<p>If you create a small project, using this technique is totally ok. The problem starts when the project starts to grow.</p>
<p>This article is about a small sized project with very few PHP files. In any case, readability is a very important thing. You know the case when you get back to your code after a long time to edit something, and you just are lost. To make the code readable and logically sound, there is a structure that can be used to achieve it.</p>
<p>If the PHP file contains HTML in it, usually it is good to separate the two. The file starts with PHP, containing all the logic needed. All the data that needs to be printed on the screen is added into variables. These variables are then used in the HTML. This clearly separates the logic from the actual data output. So the structure looks something like:</p><pre class="crayon-plain-tag">&amp;lt;?php 
// PHP code here $variable = 'Hello, world'; 
$variable = 'Hello, world!';
?&amp;gt;
&amp;lt;!-- HTML part here --&amp;gt;
&amp;lt;div&amp;gt;&amp;lt;?php echo $variable; ?&amp;gt;&amp;lt;/div&amp;gt;</pre><p>In the PHP section, where the logic is, you can also separate the logic that handles POST requests for example. It is good practice to create variables that will control such events and that hold information about these events. These variables than can control the HTML part accordingly. For example:</p><pre class="crayon-plain-tag">&nbsp;&amp;lt;?php
$error = '';
$post_var = '';
$was_post = false;
// Some data collecting logic
$variable = 'Hello, world!';
if ($_POST)
{
&nbsp;&nbsp; &nbsp;$error = 'Sample error.';
&nbsp;&nbsp; &nbsp;$post_var = 'Goodbye';
&nbsp;&nbsp; &nbsp;$was_post = true;
}
?&amp;gt;
&amp;lt;?php if ($error != ''): ?&amp;gt;
&nbsp;&nbsp; &nbsp;&amp;lt;div style=&quot;color:red;&quot;&amp;gt;&amp;lt;?php echo $error; ?&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;?php endif! ?&amp;gt;
&amp;lt;div&amp;gt;&amp;lt;?php echo $variable; ?&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;?php if ( $was_post ): ?&amp;gt;
&nbsp;&nbsp; &nbsp;&amp;lt;div&amp;gt;&amp;lt;?php echo $post_var; ?&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;?php endif; ?&amp;gt;
&amp;lt;form action=&quot;&quot; method=&quot;post&quot;&amp;gt;
&nbsp;&nbsp; &nbsp;&amp;lt;input type=&quot;submit&quot; value=&quot;POST&quot;&amp;gt;
&amp;lt;/form&amp;gt;</pre><p>This makes your code clear and if needed, later you can separate the logic from the actual html. Using such a structure is beneficial for you. Since PHP is a very loose language, you are the one that needs to pay attention to such things, but you will not regret it.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.gadratilprogramming.net/how-to-structure-a-basic-php-file/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
