array_pop() with Key - php

Consider the following array
$array = array('fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese');
I wanted to use array_pop to get the last key/value pair.
However, one will note that after the following
$last = array_pop($array);
var_dump($last);
It will output only the value (string(6) "cheese")
How can I "pop" the last pair from the array, preserving the key/value array structure?

Check out array_slice() http://php.net/manual/en/function.array-slice.php
Last argument true is to preserve keys.
When you pass the offset as negative, it starts from the end. It's a nice trick to get last elements without counting the total.
$array = [
"a" => 1,
"b" => 2,
"c" => 3,
];
$lastElementWithKey = array_slice($array, -1, 1, true);
print_r($lastElementWithKey);
Outputs:
Array
(
[c] => 3
)

try
end($array); //pointer to end
each($array); //get pair

You can use end() and key() to the the key and the value, then you can pop the value.
$array = array('fruit' => 'apple', 'vegetable' => 'potato', 'dairy' => 'cheese');
$val = end($array); // 'cheese'
// Moves array pointer to end
$key = key($array); // 'dairy'
// Gets key at current array position
array_pop($array); // Removes the element
// Resets array pointer

Why not using new features? The following code works as of PHP 7.3:
// As simple as is!
$lastPair = [array_key_last($array) => array_pop($array)];
The code above is neat and efficient (as I tested, it's about 20% faster than array_slice() + array_pop() for an array with 10000 elements; and the reason is that array_key_last() is really fast). This way the last value will also be removed.
Tip: You can also extract key and value separately:
[$key, $value] = [array_key_last($array), array_pop($array)];

This should work, just don't do it inside a foreach loop (it'll mess up the loop)
end($array); // set the array pointer to the end
$keyvaluepair = each($array); // read the key/value
reset($array); // for good measure
Edit: Briedis suggests array_slice() which is probably a better solution

Another option:
<?php
end($array);
list($key, $value) = each($array);
array_pop($array);
var_dump($key, $value);
?>

Try this:
<?php
function array_end($array)
{
$val = end($array);
return array(array_search($val, $array) => $val);
}
$array = array(
'fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese'
);
echo "<pre>";
print_r(array_end($array));
?>
Output:
Array
(
[dairy] => cheese
)

Related

How can i convert ARRAY into VARIABLE? [duplicate]

I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?
If you have a value and want to find the key, use array_search() like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key will now contain the key for value 'a' (that is, 'first').
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
If the name's dynamic, then you must have something like
$arr[$key]
which'd mean that $key contains the value of the key.
You can use array_keys() to get ALL the keys of an array, e.g.
$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);
would give you
$x = array(0 => 'a', 1 => 'c');
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Yes you can infact php is one of the few languages who provide such support..
foreach($arr as $key=>$value)
{
}
if you need to return an array elements with same value, use array_keys() function
$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));
use array_keys() to get an array of all the unique keys.
Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].
http://php.net/manual/en/function.array-keys.php
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual

A better way to randomly select a key and value pair from an array in PHP

As far as I know array_rand() can only grab a radnom array from an array like this:
$array = array( 'apple', 'orange', 'banana' );
$two_random_items = array_rand( $array , 2 ); // outputs i.e. orange and banana
But how can I grab 2 random items but with the key value array? Like this?
$array = array( '0' => 'apple', '1' => 'orange', '2' => 'banana' );
$rand_keys = array_rand($array, 2);
$rand_values = array();
foreach ($rand_keys as $key) {
$rand_values[] .= $array[$key];
}
That's probably not the right way and it's a lot of code.
I have a big array this is just an example and I need to grab 1000+ or more items randomly from the parent array and put them in a new array, keys can be reset, this is not important. The value part has to stay the same, of course.
Is there a better way how to achieve this?
Just shuffle and slice 2:
shuffle($array);
$rand_values = array_slice($array, 0, 2);
First, this line: $rand_values[] .= $array[$key]; is wrong. The .= operator is to join strings, to add a value to the end of the array, you just need $rand_values[] = $array[$key];.
If you don't care about the keys, just use array_values function to "dump" the keys.
$array = array('a' => 'orange', 'c' => 'banana', 'b' => 'peach');
$two_random_items = array_rand(array_values($array) , 2 );
array_values will strip down the keys, and will return an array with the values (the keys will become 0, 1, 2...)

PHP - Associative arrays: Changing keys for key value pair where value is a class object

I have an associative array of the form:
$input = array("one" => <class object1>,
"two" => <class object2,
... //and so on);
The keys of $input are guaranteed to be unique. I also have a method called moveToHead($key) which moves the $input[$key] element to the 0th location of this associative array. I have few questions:
Is it possible to determine the index of an associative array?
How to move the array entry for corresponding $key => $value pair to the index 0 and retaining the $key as is?
What could be the best possible way to achieve both of the above points?
I was thinking to do array_flip for 2nd point (a sub solution), but later found out that array_flip can only be done when array elements are int and string only. Any pointers?
With a function called array_keys you can determine the index of a key:
$keys = array_flip(array_keys($input));
printf("Index of '%s' is: %d\n", $key, $keys[$key]);
To insert an array at a certain position (for example at the beginning), there is the array_splice function. So you can create the array to insert, remove the value from the old place and splice it in:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
array_splice($input, 0, 0, array($key => $value));
Something similar is possible with the array union operator, but only because you want to move to the top:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
$result = array($key => $value) + $input;
But I think this might have more overhead than array_splice.
The "index" of an associative array is the key. In a numerically indexed array, the "key" is the index number.
EDIT: I take it back. PHP's associative arrays are ordered (like Ordered Maps in other languages).
But perhaps what you really want is an ordered array of associative arrays?
$input = array(array("one" => <class object1>),
array("two" => <class object2>)
//...
);
Here's what I came up with:
$arr = array('one' => 'Value1', 'two' => 'Value2', 'three' => 'Value3');
function moveToHead($array,$key) {
$return = $array;
$add_val = array($key => $return[$key]);
unset($return[$key]);
return $add_val + $return;
}
print_r(moveToHead($arr,'two'));
results in
Array
(
[two] => Value2
[one] => Value1
[three] => Value3
)
http://codepad.org/Jcb6ebxZ
You can use internal array pointer functions to do what you want:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
reset($input); // Move to first element.
echo key($input); // "one"
You can unset the element out and put it in the front:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
$key = "two";
$element = $input[$key];
unset($input[$key]);
// Complicated associative array unshift:
$input = array_reverse($input);
$input[$key] = $element;
$input = array_reverse($input);
print_r($input);

PHP - Get key name of array value

I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?
If you have a value and want to find the key, use array_search() like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key will now contain the key for value 'a' (that is, 'first').
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
If the name's dynamic, then you must have something like
$arr[$key]
which'd mean that $key contains the value of the key.
You can use array_keys() to get ALL the keys of an array, e.g.
$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);
would give you
$x = array(0 => 'a', 1 => 'c');
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Yes you can infact php is one of the few languages who provide such support..
foreach($arr as $key=>$value)
{
}
if you need to return an array elements with same value, use array_keys() function
$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));
use array_keys() to get an array of all the unique keys.
Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].
http://php.net/manual/en/function.array-keys.php
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual

array_splice() - Numerical Offsets of Associative Arrays

I'm trying to do something but I can't find any solution, I'm also having some trouble putting it into works so here is a sample code, maybe it'll be enough to demonstrate what I'm aiming for:
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
);
Now, I want to use array_splice() to remove (and return) one element from the array:
$spliced = key(array_splice($input, 2, 1)); // I'm only interested in the key...
The above will remove and return 1 element (third argument) from $input (first argument), at offset 2 (second argument), so $spliced will hold the value more.
I'll be iterating over $input with a foreach loop, I know the key to be spliced but the problem is I don't know its numerical offset and since array_splice only accepts integers I don't know what to do.
A very dull example:
$result = array();
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, 2 /* How do I know its 2? */, 1));
}
}
I first though of using array_search() but it's pointless since it'll return the associative index....
How do I determine the numerical offset of a associative index?
Just grabbing and unsetting the value is a much better approach (and likely faster too), but anyway, you can just count along
$result = array();
$idx = 0; // init offset
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, $idx, 1));
}
$idx++; // count offset
}
print_R($result);
print_R($input);
gives
Array
(
[0] => more
)
Array
(
[who] => me
[what] => car
[when] => today
)
BUT Technically speaking an associative key has no numerical index. If the input array was
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
'foo', 'bar', 'baz'
);
then index 2 is "baz". But since array_slice accepts an offset, which is not the same as a numeric key, it uses the element found at that position in the array (in order the elements appear), which is why counting along works.
On a sidenote, with numeric keys in the array, you'd get funny results, because you are testing for equality instead of identity. Make it $key === 'more' instead to prevent 'more' getting typecasted. Since associative keys are unique you could also return after 'more' was found, because checking subsequent keys is pointless. But really:
if(array_key_exists('more', $input)) unset($input['more']);
I found the solution:
$offset = array_search('more', array_keys($input)); // 2
Even with "funny" arrays, such as:
$input = array
(
'who' => 'me',
'what' => 'car',
'more' => 'car',
'when' => 'today',
'foo', 'bar', 'baz'
);
This:
echo '<pre>';
print_r(array_keys($input));
echo '</pre>';
Correctly outputs this:
Array
(
[0] => who
[1] => what
[2] => more
[3] => when
[4] => 0
[5] => 1
[6] => 2
)
It's a trivial solution but somewhat obscure to get there.
I appreciate all the help from everyone. =)
$i = 0;
foreach ($input as $key => $value)
{
if ($key == 'more')
{
// Remove the index "more" from $input and add it to $result.
$result[] = key(array_splice($input, $i , 1));
}
$i++;
}

Categories