reverse first array element with last - php

I'm trying to reverse first element of array given in parameter of my function with last element.
here is my try so far:
$my_array = [0, 1, 2, 3, 4];
function reverse_start_with_last(array &$arr)
{
$arr[0] = end($arr);
$last = end($arr);
$last = reset($arr);
print_r($arr);
static $callingnumber = 0;
$callingnumber++;
echo '<br><br>' . $callingnumber;
}
reverse_start_with_last($my_array);
it outputs:
Array ( [0] => 4 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ).
so as you can see zero is reversed with 4 but 4 is not reversed with 0..
Thanks in advance !

There are a few ways to do it, the problem is that your code overwrites the start before it stores it and tries to move it. This code takes the value, then overwrites it and then updates the last item...
function reverse_start_with_last(array &$arr)
{
$first = $arr[0];
$arr[0] = end($arr);
$arr[count($arr)-1] = $first;
print_r($arr);
}
reverse_start_with_last($my_array);
This assumes a numerically indexed array and not any other form of indexing.

This function swap the first with the last element of the array.
function array_change_first_last(array &$arr)
{
$last = end($arr);
$arr[key($arr)] = reset($arr);
$arr[key($arr)] = $last;
}
$my_array = [0, 1, 2, 3, 4];
array_change_first_last($my_array);
This function works with numeric and associative arrays alike. The keys remain, only the values ​​are exchanged.
$ass_array = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'z'=> 4];
array_change_first_last($ass_array);
Result:
array(5) { ["a"]=> int(4) ["b"]=> int(1) ["c"]=> int(2) ["d"]=> int(3) ["z"]=> int(0) }

You can shift the first element and pop the last and store them and then unshift the last and push the first
$my_array = [0, 1, 2, 3, 4];
function reverse_start_with_last(array &$arr)
{
$first = array_shift($arr); // remove the first element and store it
$last = array_pop($arr); // remove the last and store it
array_unshift($arr, $last); // add the last at the beginning of the array
array_push($arr, $first); // add the first at the end of the array
}
reverse_start_with_last($my_array);
print_r($my_array)

Related

How can I merge two associative arrays and preserve the global order of the entries?

I have two arrays like this:
$arr1 = ['a' => '1','b' => 2];
$arr2 = ['h' => 'c','j' => '3'];
And I want to merge them to this result:
$newArr = ['a' => '1','h'=>'c','b'=>2,'j' => '3'];
That means I want to merge them so that the global order of the entries is the same as in the source arrays. In other words, zip and flatten.
array_merge does not do this. Is there any solution?
Note that this solution will only work if the two arrays have the same length:
$arr1 = [ 'a' => '1', 'b' => 2 ];
$arr2 = [ 'h' => 'c', 'j' => '3' ];
$count = count($arr1);
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$result = [];
for ($i = 0; $i < $count; $i++) {
$key1 = $keys1[$i];
$result[$key1] = $arr1[$key1];
$key2 = $keys2[$i];
$result[$key2] = $arr2[$key2];
}
print_r($result);
Output:
Array
(
[a] => 1
[h] => c
[b] => 2
[j] => 3
)
Edited based on mickmackusa's comment below.
First is a solution that will consume the input arrays in a loop while building the new structure. You can always cache separate copies of the input if you need them elsewhere.
All solutions below will work even if the two arrays have different lengths -- any remaining elements will be appended to the end of the result array after the loop.
Code: (Demo)
$result = [];
while ($arr1 && $arr2) {
$result += array_splice($arr1, 0, 1)
+ array_splice($arr2, 0, 1);
}
$result += $arr1 + $arr2;
var_export($result);
Another way without consuming the input arrays is to build lookup arrays:
Code: (Demo)
$max = max(count($arr1), count($arr2));
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$result = [];
for ($x = 0; $x < $max; ++$x) {
if (isset($keys1[$x])) {
$result[$keys1[$x]] = $arr1[$keys1[$x]];
}
if (isset($keys2[$x])) {
$result[$keys2[$x]] = $arr2[$keys2[$x]];
}
}
var_export($result);
Or you could use array_slice() to isolate one element at a time from each array without damaging the input arrays, nor generating warnings.
Code: (Demo)
$result = [];
for ($i = 0, $count = count($arr1); $i < $count; ++$i) {
$result += array_slice($arr1, $i, 1)
+ array_slice($arr2, $i, 1);
}
$result += $arr1 + $arr2;
You can use array_merge() or array_merge_recursive().
Merges the elements of one or more arrays such that the values of one array are appended to the end of the previous one. The result of the function is a new array.
https://www.php.net/manual/ru/function.array-merge.php
The array_merge_recursive() function merges the elements of two or more arrays in such a way that the values ​​of one array are appended to the end of the other. Returns the resulting array.
If the input arrays have the same string keys, then the values ​​of those keys are merged into an array, and this is done recursively, so that if one of the values ​​is an array, then the function merges it with the corresponding value in the other array. However, if the arrays have the same numeric keys, each successive value will not replace the original value, but will be added to the end of the array.
https://www.php.net/manual/ru/function.array-merge-recursive.php
you can use array_merge function,which uses to merge two or more arrays into single array.
$arr1 = ['a' => '1','b' => 2];
$arr2 = ['h' => 'c','j' => '3'];
$result=array_merge($arr1,$arr2);
var_dump($result);
//output:- array(4) { ["a"]=> string(1) "1" ["b"]=> int(2) ["h"]=> string(1) "c" ["j"]=> string(1) "3" }

Merge associative arrays by partial key match

I have an array:
$a = [
"g41" => 1,
"g44" => 2,
"g53" => 3
];
And another array is:
$list = [
40,
41,
44,
46,
53
];
How to combine these arrays by partial key matches to produce the following results?
$result = [
"41" => 1,
"44" => 2,
"53" => 3,
"40" => null,
"46" => null
];
Iterate $list array and check for the key in the other $a array:
$a = array("g41" => 1, "g44" => 2, "g53" => 3);
$list = array(40, 41, 44, 46, 53);
$result = [];
foreach ($list as $key) {
$result[$key] = $a["g$key"] ?? null;
}
var_dump($result);
Output:
array(5) {
[40]=> NULL
[41]=> int(1)
[44]=> int(2)
[46]=> NULL
[53]=> int(3)
}
since you want to the result sequence follow $a, you may need to unset $list, and push remaining lists to $result
sample code as below:
<?php
$a=["g41"=>1,"g44"=>2,"g53"=>3];
$list=[40,41,44,46,53];
$result =[];
foreach($a as $key => $value){
$new_key = substr($key,1); //remove first character, if only you first key always single char, else you may use your own method to extract key
if(in_array($new_key,$list)){
$result[$new_key] = $value;
unset($list[array_search($new_key, $list)]);//remove used key
}
}
//push remaining as null
foreach($list as $v){
$result[$v] = null;
}
print_r($result);
write your custom script
$result = [];
foreach($a as $key => $value) $result[trim($key, 'g')] = $value;
foreach($list as $key) if (!isset($result[strval($key)]) $result[strval($key)] = null;
Loop the $list array
Check if the list value (prepended with g) exists in the $a array. If so, push it with the desired numeric key into the result array; if not, push it into an alternative array with the desired numeric key and the default value of null.
When finished iterating, append the data from the alternative array to the result array.
This will properly filter your data, apply the expected default values and sort the output exactly as requested.
Code: (Demo)
foreach ($list as $v) {
if (isset($a["g$v"])) {
$result[$v] = $a["g$v"];
} else {
$extra[$v] = null;
}
}
var_export(
array_replace($result ?? [], $extra ?? [])
);
I am using ?? [] to fallback to an empty array in case either of the arrays are never declared (never receive any elements).
It looks like what you want to do first is transform the keys in array $a. Then use your $list of keys to populate null values where none are present in $a.
$aKeys = preg_replace('/\D/', '', array_keys($a));
$a = array_combine($aKeys, $a);
$defaultList = array_fill_keys($list, null);
$list = array_merge($defaultList, $a);

Map an array of values to an array of each value's rank in the array

I have a array like this:
$row_arr_1=array(7,9,5,10);
now I want to get the result array like this:
$row_arr_2=array(3,2,4,1);
Explanation:
As 10 is the largest value in row_arr_1, then it will be replaced with value 1.
Similarly, as 9 is the 2nd highest value of row_arr_1, then it will be replaced by 2 and so on.
I tried to sort the values of row_arr_1 but the position is changed.
How
can i get my desired result?
It can be done using rsort() and array_search()
$row_arr_1=array(7,9,5,10);
$row_copy = $row_arr_1;
$row_arr_2 = array();
rsort($row_copy);
foreach($row_arr_1 as $val) {
$row_arr_2[] = array_search($val, $row_copy) + 1;
}
print_r($row_arr_2);
https://eval.in/990078
You can use arsort() to sort the array while preserving keys, and use those keys for your array via array_keys():
$row_arr_1 = array(7,9,5,10);
$row_arr_1_backup = $row_arr_1;
arsort($row_arr_1_backup);
$row_arr_2 = array_keys($row_arr_1_backup);
asort($row_arr_2);
$row_arr_2 = array_keys($row_arr_2);
array_walk($row_arr_2, function(&$item, &$key) {
$item = $item + 1;
});
You have to duplicate the original array, since arsort will sort the actual array it points to, rather than returning a new array.
$row_arr_1_old = array(7, 9, 5, 10);
$row_arr_1 = array(7, 9, 5, 10);
rsort($row_arr_1);
$test = [];
foreach ($row_arr_1_old as $key => $value) {
$test[] = array_search($value, $row_arr_1);
}
print_r($test);
For best efficiency try to reduce total function calls; this especially means minimizing / eliminating iterated function calls.
This is my slightly more efficient version of ahsan's answer.
Code: (Demo)
$copy = $arr = [7, 9, 5, 10];
rsort($arr); // generates: [10, 9, 7, 5]
$flipped = array_flip($arr); // generates: [10 => 0, 9 => 1, 7 => 2, 5 => 3]
foreach($copy as $v) {
$result[] = ++$flipped[$v]; // adds one to each accessed value from $flipped
}
var_export($result);
Output:
array (
0 => 3,
1 => 2,
2 => 4,
3 => 1,
)

PHP append one array to another (not array_push or +)

How to append one array to another without comparing their keys?
$a = array( 'a', 'b' );
$b = array( 'c', 'd' );
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d )
If I use something like [] or array_push, it will cause one of these results:
Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) )
//or
Array( [0]=>c [1]=>d )
It just should be something, doing this, but in a more elegant way:
foreach ( $b AS $var )
$a[] = $var;
array_merge is the elegant way:
$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b);
// $merge is now equals to array('a','b','c','d');
Doing something like:
$merge = $a + $b;
// $merge now equals array('a','b')
Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.
Another way to do this in PHP 5.6+ would be to use the ... token
$a = array('a', 'b');
$b = array('c', 'd');
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
This will also work with any Traversable
$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
A warning though:
in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
in PHP 7.3 a warning will be raised if $b is not traversable
Why not use
$appended = array_merge($a,$b);
Why don't you want to use this, the correct, built-in method.
It's a pretty old post, but I want to add something about appending one array to another:
If
one or both arrays have associative keys
the keys of both arrays don't matter
you can use array functions like this:
array_merge(array_values($array), array_values($appendArray));
array_merge doesn't merge numeric keys so it appends all values of $appendArray. While using native php functions instead of a foreach-loop, it should be faster on arrays with a lot of elements.
Addition 2019-12-13:
Since PHP 7.4, there is the possibility to append or prepend arrays the Array Spread Operator way:
$a = [3, 4];
$b = [1, 2, ...$a];
As before, keys can be an issue with this new feature:
$a = ['a' => 3, 'b' => 4];
$b = ['c' => 1, 'a' => 2, ...$a];
"Fatal error: Uncaught Error: Cannot unpack array with string keys"
$a = [3 => 3, 4 => 4];
$b = [1 => 1, 4 => 2, ...$a];
array(4) {
[1]=>
int(1)
[4]=>
int(2)
[5]=>
int(3)
[6]=>
int(4)
}
$a = [1 => 1, 2 => 2];
$b = [...$a, 3 => 3, 1 => 4];
array(3) {
[0]=>
int(1)
[1]=>
int(4)
[3]=>
int(3)
}
<?php
// Example 1 [Merging associative arrays. When two or more arrays have same key
// then the last array key value overrides the others one]
$array1 = array("a" => "JAVA", "b" => "ASP");
$array2 = array("c" => "C", "b" => "PHP");
echo " <br> Example 1 Output: <br>";
print_r(array_merge($array1,$array2));
// Example 2 [When you want to merge arrays having integer keys and
//want to reset integer keys to start from 0 then use array_merge() function]
$array3 =array(5 => "CSS",6 => "CSS3");
$array4 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 2 Output: <br>";
print_r(array_merge($array3,$array4));
// Example 3 [When you want to merge arrays having integer keys and
// want to retain integer keys as it is then use PLUS (+) operator to merge arrays]
$array5 =array(5 => "CSS",6 => "CSS3");
$array6 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 3 Output: <br>";
print_r($array5+$array6);
// Example 4 [When single array pass to array_merge having integer keys
// then the array return by array_merge have integer keys starting from 0]
$array7 =array(3 => "CSS",4 => "CSS3");
echo " <br> Example 4 Output: <br>";
print_r(array_merge($array7));
?>
Output:
Example 1 Output:
Array
(
[a] => JAVA
[b] => PHP
[c] => C
)
Example 2 Output:
Array
(
[0] => CSS
[1] => CSS3
[2] => JAVASCRIPT
[3] => HTML
)
Example 3 Output:
Array
(
[5] => CSS
[6] => CSS3
[8] => JAVASCRIPT
[9] => HTML
)
Example 4 Output:
Array
(
[0] => CSS
[1] => CSS3
)
Reference Source Code
Following on from answer's by bstoney and Snark I did some tests on the various methods:
// Test 1 (array_merge)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
$array1 = array_merge($array1, $array2);
printf("Test 1: %.06f\n", microtime(true) - $start);
// Test2 (foreach)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
foreach ($array2 as $v) {
$array1[] = $v;
}
printf("Test 2: %.06f\n", microtime(true) - $start);
// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
array_push($array1, ...$array2);
printf("Test 3: %.06f\n", microtime(true) - $start);
Which produces:
Test 1: 0.002717
Test 2: 0.006922
Test 3: 0.004744
ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.
Whilst method 3 isn't strictly an answer to the criteria of 'not array_push' in the question, it is one line and the most high performance in all respects, I think the question was asked before the ... syntax was an option.
UPDATE 25/03/2020:
I've updated the test which was flawed as the variables weren't reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn't have been affected by the testing flaw.
So, the saga continues, I will start using array_merge from now on!
For big array, is better to concatenate without array_merge, for avoid a memory copy.
$array1 = array_fill(0,50000,'aa');
$array2 = array_fill(0,100,'bb');
// Test 1 (array_merge)
$start = microtime(true);
$r1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);
// Test2 (avoid copy)
$start = microtime(true);
foreach ($array2 as $v) {
$array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);
// Test 1: 0.004963
// Test 2: 0.000038
Since PHP 7.4 you can use the ... operator. This is also known as the splat operator in other languages, including Ruby.
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Output
array(5) {
[0]=>
string(6) "banana"
[1]=>
string(6) "orange"
[2]=>
string(5) "apple"
[3]=>
string(4) "pear"
[4]=>
string(10) "watermelon"
}
Splat operator should have better performance than array_merge. That’s not only because the splat operator is a language structure while array_merge is a function, but also because compile time optimization can be performant for constant arrays.
Moreover, we can use the splat operator syntax everywhere in the array, as normal elements can be added before or after the splat operator.
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = [...$arr1, ...$arr2];
$arr4 = [...$arr1, ...$arr3, 7, 8, 9];
Before PHP7 you can use:
array_splice($a, count($a), 0, $b);
array_splice() operates with reference to array (1st argument) and puts array (4th argument) values in place of list of values started from 2nd argument and number of 3rd argument. When we set 2nd argument as end of source array and 3rd as zero we append 4th argument values to 1st argument
if you want to merge empty array with existing new value. You must initialize it first.
$products = array();
//just example
for($brand_id=1;$brand_id<=3;$brand_id++){
array_merge($products,getByBrand($brand_id));
}
// it will create empty array
print_r($a);
//check if array of products is empty
for($brand_id=1;$brand_id<=3;$brand_id++){
if(empty($products)){
$products = getByBrand($brand_id);
}else{
array_merge($products,getByBrand($brand_id));
}
}
// it will create array of products
Hope its help.
foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.
// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
$chars[] = array_fill(0, 10, 'a');
}
// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
$new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec
// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
foreach ($splitArray as $value) {
$new[] = $value;
}
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster

How to add an array value to the middle of an associative array?

Lets say I have this array:
$array = array('a'=>1,'z'=>2,'d'=>4);
Later in the script, I want to add the value 'c'=>3 before 'z'. How can I do this?
Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc()
The keys I used above are placeholders. Using ksort() will not achieve what I want.
http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.
Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'
Am I missing something?
$key = 'z';
$offset = array_search($key, array_keys($array));
$result = array_merge
(
array_slice($array, 0, $offset),
array('c' => 3),
array_slice($array, $offset, null)
);
Handling of nonexistent keys (appending $data by default):
function insertBeforeKey($array, $key, $data = null)
{
if (($offset = array_search($key, array_keys($array))) === false) // if the key doesn't exist
{
$offset = 0; // should we prepend $array with $data?
$offset = count($array); // or should we append $array with $data? lets pick this one...
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
Demo:
$array = array('a' => 1, 'z' => 2, 'd' => 4);
// array(4) { ["a"]=> int(1) ["c"]=> int(3) ["z"]=> int(2) ["d"]=> int(4) }
var_dump(insertBeforeKey($array, 'z', array('c' => 3)));
// array(4) { ["a"]=> int(1) ["z"]=> int(2) ["d"]=> int(4) ["c"]=> int(3) }
var_dump(insertBeforeKey($array, 'y', array('c' => 3)));
A simple approach to this is to iterate through the original array, constructing a new one as you go:
function InsertBeforeKey( $originalArray, $originalKey, $insertKey, $insertValue ) {
$newArray = array();
$inserted = false;
foreach( $originalArray as $key => $value ) {
if( !$inserted && $key === $originalKey ) {
$newArray[ $insertKey ] = $insertValue;
$inserted = true;
}
$newArray[ $key ] = $value;
}
return $newArray;
}
Then simply call
$array = InsertBeforeKey( $array, 'd', 'c', 3 );
According to your original question the best answer I can find is this:
$a = array('a'=>1,'z'=>2,'d'=>4);
$splitIndex = array_search('z', array_keys($a));
$b = array_merge(
array_slice($a, 0, $splitIndex),
array('c' => 3),
array_slice($a, $splitIndex)
);
var_dump($b);
array(4) {
["a"]=>
int(1)
["c"]=>
int(3)
["z"]=>
int(2)
["d"]=>
int(4)
}
Depending on how big your arrays are you will duplicate quite some data in internal memory, regardless if you use this solution or another.
Furthermore your fifth edit seems to indicate that alternatively your SQL query could be improved. What you seem to want to do there would be something like this:
SELECT a, b, CONCAT(a, ' ', b) AS ab FROM ... WHERE ...
If changing your SELECT statement could make the PHP solution redundant, you should definitely go with the modified SQL.
function insertValue($oldArray, $newKey, $newValue, $followingKey) {
$newArray = array ();
foreach (array_keys($oldArray) as $k) {
if ($k == $followingKey)
$newArray[$newKey] = $newValue;
$newArray[$k] = $oldArray [$k];
}
return $newArray;
}
You call it as
insertValue($array, 'c', '3', 'z')
As for Edit 5:
edit your sql, so that it reads
SELECT ..., pizza, drink, pizza+drink as full_meal, ... FROM ....
and you have the column automatically:
Array (
...
'pizza' => 12,
'drink' => 5,
'full_meal' => 17,
...
)
Associative arrays are not ordered, so you can simply add with $array['c'] = 3.
If order is important, one option is switch to a data structure more like:
$array = array(
array('a' => 1),
array('b' => 2)
array('d' => 4)
);
Then, use array_splice($array, 2, 0, array('c' => 3)) to insert at position 2. See manual on array_splice.
An alternative approach is to supplement the associative array structure with an ordered index that determines the iterative order of keys. For instance:
$index = array('a','b','d');
// Add new value and update index
$array['c'] = 3;
array_splice($index, 2, 0, 'c');
// Iterate the array in order
foreach $index as $key {
$value = $array[$key];
}
You can define your own sortmap when doing a bubble-sort by key. It's probably not terribly efficient but it works.
<pre>
<?php
$array = array('a'=>1,'z'=>2,'d'=>4);
$array['c'] = 3;
print_r( $array );
uksort( $array, 'sorter' );
print_r( $array );
function sorter( $a, $b )
{
static $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
return $ordinality[$a] - $ordinality[$b];
}
?>
</pre>
Here's an approach based on ArrayObject using this same concept
$array = new CitizenArray( array('a'=>1,'z'=>2,'d'=>4) );
$array['c'] = 3;
foreach ( $array as $key => $value )
{
echo "$key: $value <br>";
}
class CitizenArray extends ArrayObject
{
static protected $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
function offsetSet( $key, $value )
{
parent::offsetSet( $key, $value );
$this->uksort( array( $this, 'sorter' ) );
}
function sorter( $a, $b )
{
return self::$ordinality[$a] - self::$ordinality[$b];
}
}
For the moment the best i can found to try to minimize the creation of new arrays are these two functions :
the first one try to replace value into the original array and the second one return a new array.
// replace value into the original array
function insert_key_before_inplace(&$base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
foreach($end as $key => $val) $base[$key] = $val;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
insert_key_before_inplace($array, 'z', 'c', 3);
var_export($array); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
// create new array
function insert_key_before($base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
return $base+$end;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
$newArray=insert_key_before($array, 'z', 'c', 3);
var_export($array); // ( 'a' => 1, 'z' => 2, 'd' => 4, )
var_export($newArray); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
function putarrayelement(&$array, $arrayobject, $elementposition, $value = null) {
$count = 0;
$return = array();
foreach ($array as $k => $v) {
if ($count == $elementposition) {
if (!$value) {
$value = $count;
}
$return[$value] = $arrayobject;
$inserted = true;
}
$return[$k] = $v;
$count++;
}
if (!$value) {
$value = $count;
}
if (!$inserted){
$return[$value];
}
$array = $return;
return $array;
}
$array = array('a' => 1, 'z' => 2, 'd' => 4);
putarrayelement($array, '3', 1, 'c');
print_r($array);
Great usage of array functions but how about this as a simpler way:
Add a static column to the SQL and then replace it in the resultant array. Order stays the same:
SQL :
Select pizza , drink , 'pizza-drink' as 'pizza-drink' , 28 columns..... From Table
Array :
$result['pizza-drink'] = $result['pizza'] . $result['drink'];
A simplified Alix Axel function if you need to just insert data in nth position:
function array_middle_push( array $array, int $position, array $data ): array {
return array_merge( array_slice( $array, 0, $position ), $data, array_slice( $array, $position ) );
}
Try this
$array['c']=3;
An associative array is not ordered by default, but if you wanted to sort them alphabetically you could use ksort() to sort the array by it's key.
If you check out the PHP article for ksort() you will se it's easy to sort an array by its key, for example:
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
// The above example will output:
a = orange
b = banana
c = apple
d = lemon
you can add it by doing
$array['c']=3;
and if you absolutely want it sorted for printing purposes, you can use php's ksort($array) function
if the keys are not sortable by ksort, then you will have to create your own sort by using php's uasort function. see examples here
http://php.net/manual/en/function.uasort.php

Categories