Set operations
Performs set operations on two lists.
Source code (hide)
Global files are not shown below.
Table of contents
index.php
back to toc
<?php
/* globals, templates */
$locals = array (
'title' => 'Set operations',
'description' => 'Performs set operations on two lists.',
'files' => array('index.php')
);
include('../globals/globals.php');
include('../globals/forms.php');
/************
** input
************/
$set_a = $_POST['set_a'];
$set_b = $_POST['set_b'];
$operation = $_POST['operation'];
$unique = $_POST['unique'];
$sort = $_POST['sort'];
// input form
?>
<form action="" method="post">
<fieldset>
<legend>Input</legend>
<p>Enter a newline-delimited list into each box, then select the set operation you want to perform.</p>
<textarea id="set_a" name="set_a" rows="12" cols="100" style="width:30em; float:left; margin-right:1em;"><?php echo $set_a; ?></textarea>
<textarea id="set_b" name="set_b" rows="12" cols="100" style="width:30em;"><?php echo $set_b; ?></textarea><br clear="all" />
Set operation:<br />
<input type="radio" id="difference" name="operation" value="difference" style="margin-left:4em;" <?php gCheckRadio($operation,'difference'); ?> />
<label for="difference">difference (A - B)</label><br />
<input type="radio" id="intersection" name="operation" value="intersection" style="margin-left:4em;" <?php gCheckRadio($operation,'intersection'); ?> />
<label for="intersection">intersection</label><br />
<input type="radio" id="union" name="operation" value="union" style="margin-left:4em;" <?php gCheckRadio($operation,'union'); ?> />
<label for="union">union</label><br />
<?php
echo checkbox('unique', $unique, 'Remove duplicate items'), '<br />';
echo checkbox('sort', $sort, 'Sort'), '<br />';
gDebugOption();
?>
<input type="submit" value="Process" />
</fieldset>
</form>
<?php
if($_POST['operation']) {
/************
** Operation
************/
// break input into arrays
$set_a = explode("\r\n", $set_a);
$set_b = explode("\r\n", $set_b);
// perform operation
switch($operation) {
case 'difference':
$result = array_diff($set_a, $set_b);
break;
case 'intersection':
$result = array_intersect($set_a, $set_b);
break;
case 'union':
$result = array_merge($set_a, $set_b);
break;
}
// filter duplicates & sort
if($unique)
$result = array_unique($result);
if($sort)
sort($result);
// merge array into output
$output = implode("\n", $result);
/************
** Output
************/
// result
echo '<h2>Result of ', $operation, '</h2>',
'<textarea rows="12" cols="100">', $output, '</textarea>';
// debug
gDebug(get_defined_vars());
}
/* globals, templates */
makeFooter();
?>
This tool is written and copyright by Jesse Plamondon-Willard (Pathoschild). You may freely use, distribute, and modify this script in any way and for any purpose, so long as you cite the above name as original author.
