In the script below, I need to add an item "None" with value of "" to the beginning of the array.
I'm using the $addFonts array below to do that, however, its being added to the select menu as "Array". What am I missing?
$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);
$addFonts = array(
'' => 'None'
);
array_push($googleFontsArray, $addFonts);
foreach($googleFontsArrayContentsArr as $font)
{
$googleFontsArray[$font['css-name']] = $font['font-name'];
}
Checkout array_unshift().
Should just be
$googleFontsArray['None'] = '';
This array is associative.
Add the first element in an array.
array_unshift()
$sampleArray = array("Cat", "Dog");
array_unshift($sampleArray ,"Horse");
print_r($sampleArray); // output array - array('horse', 'cat', 'dog')
Remove first element from an array.
array_shift()
Perhaps you want to use
array_merge($googleFontsArray, $addFonts);
?
If you just want to add one element to the beginning of an existing array, use array_unshift():
http://www.php.net/manual/en/function.array-unshift.php
Here is a complete list of array functions:
http://www.php.net/manual/en/ref.array.php
You can use the addition operator:
$a = array('Foo' => 42);
$a = array('None' => null) + $a;
Note that most people would consider it bad practice to let the position of a pair be significant, when using associative arrays. This is unique for php - other languages have either vectors (non-associative arrays) or hashmaps (Associative arrays).
Related
Let's say I have an array like so:
array(
[0]=>1
[1]=>3
[3]=>5
[15]=>6
);
Arbitrarily I want array[15] to be the first:
array(
[15]=>6
[0]=>1
[1]=>3
[3]=>5
);
What is the fastest and most painless way to do this?
Here are the things I've tried:
array_unshift - Unfortunately, my keys are numeric and I need to keep the order (sort of like uasort) this messes up the keys.
uasort - seems too much overhead - the reason I want to make my element the first in my array is to specifically avoid uasort! (Swapping elements on the fly instead of sorting when I need them)
Assuming you know the key of the element you want to shift, and that element could be in any position in the array (not necessarily the last element):
$shift_key = 15;
$shift = array($shift_key => $arr[$shift_key]);
$arr = $shift + $arr;
See demo
Updated - unset() not necessary. Pointed out by #FuzzyTree
You can try this using a slice and a union operator:
// get last element (preserving keys)
$last = array_slice($array, -1, 1, true);
// put it back with union operator
$array = $last + $array;
Update: as mentioned below, this answer takes the last key and puts it at the front. If you want to arbitrarily move any element to the front:
$array = array($your_desired_key => $array[$your_desired_key]) + $array;
Union operators take from the right and add to the left (so the original value gets overwritten).
If #15 is always last you can do
$last = array_pop($array); //remove from end
array_unshift($last); //push on front
To reorder the keys for sorting simply add
$array = array_values($array); //reindex array
#Edit - if we don't assume its always last then I would go with ( if we always know wwhat the key is, then most likely we will know its position or it's not a numerically indexed array but an associative one with numeric keys, as op did state "arbitrarily" so one has to assume the structure of the array is known before hand. )
I also dont see the need to reindex them as the op stated that it was to avoid sorting. So why would you then sort?
$item = $array[15];
unset($array[15]); //....etc.
If I have the following array. What would be the best way to add a element to list[] for the last element of $myArray[]? Note that list[] has numerical indexes (i.e. not associative). Thanks!
$myArray[] = array( 'name' => 'hello', 'list' => array() );
If $myArray is not associative
array_push($myArray[count($myArray)-1]['list'], 'new element');
or
$myArray[count($myArray)-1]['list'][] = 'new element';
with this method you change the position of the array pointer.
You can do it like this:
$last = array_pop($myArray); // remove last element of array
$last['list'][] = "new element"; // add element to array
$myArray[] = $last; // add changed last element again
$myArray[count($myArray)-1]['list'][]="something to go in 'list' array";//this shall append
//to the second dimension array with keyname 'list'
There is actually a more beautiful way (in my opinion):
$ref = &$myArray[];
$ref['list'][] = 'new item'
As you can see $ref - is reference to the last element of $myArray, so you can change the last element by changing $ref;
array_push function do that.
array_push()
All I need to two is remove the final two elements from an array, which only contains 3 elements, output those two removed elements and then output the non-removed element. I'm having trouble removing the two elements, as well as keeping their keys.
My code is here http://pastebin.com/baV4fMxs
It is currently outputting : Java
Perl
Array
I want it to output:
[One] => Perl and [Two] => Java
[Zero] => PHP
$last=array_splice($inputarray,-1);
//$last has now key=>value of last element
$middle=array_splice($inputarray,-1);
//$middle has now key=>value of middle element
//$inputarray has now only key=>value of first element
It seems to me that you want to retrieve those two values being removed before getting rid of them. With this in mind, I suggest the use of array_pop() which simultaneously returns the last item in the array and removes it from the array.
$val = array_pop($my_array);
echo $val; // Last value
$val = array_pop($my_array);
echo $val; // Middle value
// Now, $my_array has only the first value
You mentioned keys, so I assume it's an associative array. In order to remove an element, you can call the unset function, like this:
unset ($my_array['my_key'])
Do this for both elements that you want to remove.
array_pop will do it for you quite easily:
$array = array( 'one', 'two', 'three');
$last = array_pop( $array); echo $last . "\n";
$second = array_pop( $array); echo $second . "\n";
echo $array[0];
Output:
three
two
one
Demo
Having a brain freeze over a fairly trivial problem. If I start with an array like this:
$my_array = array(
'monkey' => array(...),
'giraffe' => array(...),
'lion' => array(...)
);
...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.
When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?
Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.
The only way I can think to do this is to remove it then add it:
$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;
array_shift is probably less efficient than unsetting the index, but it works:
$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
$my_array['monkey'] = array_shift($my_array);
print_r($my_array);
Another alternative is with a callback and uksort:
uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.
I really like #Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:
$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);
Demo
Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).
You can implement some basic calculus and get a universal function for moving array element from one position to the other.
For PHP it looks like this:
function magicFunction ($targetArray, $indexFrom, $indexTo) {
$targetElement = $targetArray[$indexFrom];
$magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom);
for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){
$targetArray[$Element] = $targetArray[$Element + $magicIncrement];
}
$targetArray[$indexTo] = $targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html
What is the fastest and easiest way to get the last item of an array whether be indexed array , associative array or multi-dimensional array?
$myArray = array( 5, 4, 3, 2, 1 );
echo end($myArray);
prints "1"
array_pop()
It removes the element from the end of the array. If you need to keep the array in tact, you could use this and then append the value back to the end of the array. $array[] = $popped_val
try this:
$arrayname[count(arrayname)-1]
I would say array_pop In the documentation: array_pop
array_pop — Pop the element off the end of array
Lots of great answers. Consider writing a function if you're doing this more than once:
function array_top(&$array) {
$top = end($array);
reset($array); // Optional
return $top;
}
Alternatively, depending on your temper:
function array_top(&$array) {
$top = array_pop($array);
$array[] = $top; // Push top item back on top
return $top;
}
($array[] = ... is preferred to array_push(), cf. the docs.)
For an associative array:
$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);
Edit: should also work for numeric index arrays