I was thinking whether this kind of concept is possible in php. First simply create an array and sort it using sort().
<?php
$integer_array = array(20,40,60,10);
sort($integer_array);
print_r($integer_array);
?>
The O/P for the following code would be
Array ( [0] => 10 [1] => 20 [2] => 40 [3] => 60 )
Now in second part i was thinking whether it would be possible to restore the exact same order in which the array was initally created.Consider this pseudo code below
<?php
//Function_name can be anything
function_name($integer_array);
print_r($integer_array);
?>
The O/P for the above code should be like this
Array ( [0] => 20 [1] => 40 [2] => 60 [3] => 10 )
Now is there any in-built function for array provided by php to perform this operation or we have to create something on our own to work this logic
Yes, you can do that.
If the original keys are important, you should not discard them when you sort the array.
If you use asort()
instead of sort()
, your sorted array will have the original keys. And then you can use ksort()
to get the original array back.
A simple example:
<?php
$integer_array = array(20,40,60,10);
print_r($integer_array);
asort($integer_array);
print_r($integer_array);
ksort($integer_array);
print_r($integer_array);
Outputs:
Array
(
[0] => 20
[1] => 40
[2] => 60
[3] => 10
)
Array
(
[3] => 10
[0] => 20
[1] => 40
[2] => 60
)
Array
(
[0] => 20
[1] => 40
[2] => 60
[3] => 10
)
You could make a class to make your arrays "transactional" by managing and storing the state within the class instance. Here is a quick class I just threw together:
class RevertableArray {
private $previous = [];
private $current = [];
public function __construct(array $data)
{
$this->previous = $data;
$this->current = $data;
}
public function sort()
{
$this->previous = $this->current;
sort($this->current);
return $this->current;
}
public function rollback()
{
$this->current = $this->previous;
return $this->current;
}
public function __toArray()
{
return $this->current;
}
}
Note that this will only keep track of one operation in the past. If you wanted to be able to continue to rollback, you'd have to store an array of "previous" variations and push/pop them from that stack.
You would use it like:
// Create instance
$array = new RevertableArray(['z', 'b', 'h']);
// Perform sort
$array->sort();
// Output sorted variation
var_dump((array) $array);
// Rollback
$array->rollback();
// Output original variation
var_dump((array) $array);