Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711
If I have an array like the following -
$numbers= array(
'One' => 1,
'Two' => 2,
'Three' => 3,
);
Is there a function I an use to add together both the values of 'One' and 'Two', and output the value?
If not, how would I go about making that simple function? (This is something i'd be interested in knowing too even if there is a predefined function.)
You have to use two array function.
array_slice() returns the sequence of elements from the array array as
specified by the offset and length parameters.
Basic Format of array_slice().
array_slice(array, start, length, preserve)
So,
start: Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
length:
Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
array_sum() returns the sum of values in an array.
Your array:
$numbers= array(
'One' => 1,
'Two' => 2,
'Three' => 3,
);
Function
echo $arr_sum = array_sum(array_slice($numbers, 0, 2));
Output:
3
I stuck with a problem: I have an array with IDs and want to assign theses IDs to a key of a associative array:
$newlinkcats = array( 'link_id' => $linkcatarray[0], $linkcatarray[1], $linkcatarray[2]);
this works fine, but I don't know how many entries in $linkcatarray. So I would like to loop or similar. But I don't know how.
no push, cause it is no array
no implode, cause it is no string
no =, cause it overrides the value before
Could anyone help?
Thanks
Jim
Why not just implode it ?
$newlinkcats = array(
'link_id' => implode(
',',
$linkcatarray
)
);
Or just do this:
// Suggested by Tularis
$newlinkcats = array(
'link_id' => $linkcatarray
);
If your $linkcatarray array is only comprised of the values you wish to assign to the link_id key, then you can simply point the key at that array:
$newlinkcats = array('link_id' => $linkcatarray);
If that array contains more values that you don't want included, then take a look at array_slice() to only grab the indexes you need:
// Grabs the first 3 values from $linkcatarray
$newlinkcats = array('link_id' => array_slice($linkcatarray, 0, 3));
If your desired indexes aren't contiguous, it may be easier to cherry-pick them and use a new array:
$newlinkcats = array('link_id' => array(
$linkcatarray[7],
$linkcatarray[13],
$linkcatarray[22],
// ...
));
I have a PHP array that has literal_key => value. I need to shift the key and value off the beginning of the array and stick it at the end (keeping the key also).
I've tried:
$f = array_shift($fields);
array_push($fields, $f);
but this loses the key value.
Ex:
$fields = array ("hey" => "there", "how are" => "you");
// run above
this yields:
$fields = array ("how are" => "you", "0" => "there");
(I need to keep "hey" and not have 0) any ideas?
As far as I can tell, you can't add an associative value to an array with array_push(), nor get the key with array_shift(). (same goes for pop/push). A quick hack could be:
$fields = array( "key0" => "value0", "key1" => "value1");
//Get the first key
reset($fields);
$first_key = key($fields);
$first_value = $fields[$first_key];
unset($fields[$first_key]);
$fields[$first_key] = $first_value;
See it work here. Some source code taken from https://stackoverflow.com/a/1028677/1216976
You could just take the 0th key $key using array_keys, then set $value using array_shift, then set $fields[$key] = $value.
Or you could do something fancy like
array_merge( array_slice($fields, 1, NULL, true),
array_slice($fields, 0, 1, true) );
which is untested but has the right idea.
How can I get the last key of an array?
A solution would be to use a combination of end and key (quoting) :
end() advances array 's internal pointer to the last element, and returns its value.
key() returns the index element of the current array position.
So, a portion of code such as this one should do the trick :
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
Will output :
string 'last' (length=4)
i.e. the key of the last element of my array.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.
Although end() seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():
$lastKey = key(array_slice($array, -1, 1, true));
As the tests say, on an array with 500000 elements, it is almost 7x faster!
Since PHP 7.3 (2018) there is (finally) function for this:
http://php.net/manual/en/function.array-key-last.php
$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )
will output
orange
I prefer
end(array_keys($myarr))
Just use : echo $array[count($array) - 1];
Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...
it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
$keys = array_keys($array);
$last = end($keys);
As of PHP7.3 you can directly access the last key in (the outer level of) an array with array_key_last()
The definitively puts much of the debate on this page to bed. It is hands-down the best performer, suffers no side effects, and is a direct, intuitive, single-call technique to deliver exactly what this question seeks.
A rough benchmark as proof: https://3v4l.org/hO1Yf
array_slice() + key(): 1.4
end() + key(): 13.7
array_key_last(): 0.00015
*test array contains 500000 elements, microtime repeated 100x then averaged then multiplied by 1000 to avoid scientific notation. Credit to #MAChitgarha for the initial benchmark commented under #TadejMagajna's answer.
This means you can retrieve the value of the final key without:
moving the array pointer (which requires two lines of code) or
sorting, reversing, popping, counting, indexing an array of keys, or any other tomfoolery
This function was long overdue and a welcome addition to the array function tool belt that improves performance, avoids unwanted side-effects, and enables clean/direct/intuitive code.
Here is a demo:
$array = ["a" => "one", "b" => "two", "c" => "three"];
if (!function_exists('array_key_last')) {
echo "please upgrade to php7.3";
} else {
echo "First Key: " , key($array) , "\n";
echo "Last Key: " , array_key_last($array) , "\n";
next($array); // move array pointer to second element
echo "Second Key: " , key($array) , "\n";
echo "Still Last Key: " , array_key_last($array);
}
Output:
First Key: a
Last Key: c // <-- unaffected by the pointer position, NICE!
Second Key: b
Last Key: c // <-- unaffected by the pointer position, NICE!
Some notes:
array_key_last() is the sibling function of array_key_first().
Both of these functions are "pointer-ignorant".
Both functions return null if the array is empty.
Discarded sibling functions (array_value_first() & array_value_last()) also would have offered the pointer-ignorant access to bookend elements, but they evidently failed to garner sufficient votes to come to life.
Here are some relevant pages discussing the new features:
https://laravel-news.com/outer-array-functions-php-7-3
https://kinsta.com/blog/php-7-3/#array-key-first-last
https://wiki.php.net/rfc/array_key_first_last
p.s. If anyone is weighing up some of the other techniques, you may refer to this small collection of comparisons: (Demo)
Duration of array_slice() + key(): 0.35353660583496
Duration of end() + key(): 6.7495584487915
Duration of array_key_last(): 0.00025749206542969
Duration of array_keys() + end(): 7.6123380661011
Duration of array_reverse() + key(): 6.7875385284424
Duration of array_slice() + foreach(): 0.28870105743408
As of PHP >= 7.3 array_key_last() is the best way to get the last key of any of an array. Using combination of end(), key() and reset() just to get last key of an array is outrageous.
$array = array("one" => bird, "two" => "fish", 3 => "elephant");
$key = array_key_last($array);
var_dump($key) //output 3
compare that to
end($array)
$key = key($array)
var_dump($key) //output 3
reset($array)
You must reset array for the pointer to be at the beginning if you are using combination of end() and key()
Try using array_pop and array_keys function as follows:
<?php
$array = array(
'one' => 1,
'two' => 2,
'three' => 3
);
echo array_pop(array_keys($array)); // prints three
?>
It is strange, but why this topic is not have this answer:
$lastKey = array_keys($array)[count($array)-1];
I would also like to offer an alternative solution to this problem.
Assuming all your keys are numeric without any gaps,
my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.
$array = array(0=>'dog', 1=>'cat');
$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];
var_dump($lastKey);
print_r($lastKeyValue);
This would give you:
int(1)
cat
You can use this:
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
end($array);
echo key($array);
Another Solution is to create a function and use it:
function endKey($array){
end($array);
return key($array);
}
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);
$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3
I just took the helper-function from Xander and improved it with the answers before:
function last($array){
$keys = array_keys($array);
return end($keys);
}
$arr = array("one" => "apple", "two" => "orange", "three" => "pear");
echo last($arr);
echo $arr(last($arr));
$array = array(
'something' => array(1,2,3),
'somethingelse' => array(1,2,3,4)
);
$last_value = end($array);
$last_key = key($array); // 'somethingelse'
This works because PHP moves it's array pointer internally for $array
The best possible solution that can be also used used inline:
end($arr) && false ?: key($arr)
This solution is only expression/statement and provides good is not the best possible performance.
Inlined example usage:
$obj->setValue(
end($arr) && false ?: key($arr) // last $arr key
);
UPDATE: In PHP 7.3+: use (of course) the newly added array_key_last() method.
Try this one with array_reverse().
$arr = array(
'first' => 01,
'second' => 10,
'third' => 20,
);
$key = key(array_reverse($arr));
var_dump($key);
Try this to preserve compatibility with older versions of PHP:
$array_keys = array_keys( $array );
$last_item_key = array_pop( $array_keys );