Adding elements to last element of array - php

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()

Related

Having trouble with a very simple PHP array issue

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

How to add an item to the beginning of an array?

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).

php: array item set to another array item (sibling)

The item 'reference' in the array is set to $array['fruit']. But no is value returned
$array = array(
'fruit'=>'apple',
'reference'=>$array['fruit']
);
example: echo $array['reference']; //the word apple should be displayed
How is this result achieved?
You are actually referencing the $array variable while creating it so it's normal it'll contain nothing.
This'll work but to be honest, it's kinda sketchy what you are doing.
$array = array('fruit' => 'apple');
$array['reference'] = $array['fruit'];
You will have to set it later, because $array isn't initialized yet while you're already assigning.
$array = array(
'fruit' => 'apple'
);
$array['reference'] = &$array['fruit'];
The ampersand will create a reference to the index fruit.
Hope this helped.
Use
$array = array();
$array['fruit'] = "apple";
$array['reference'] = $array['fruit'];

PHP: Remove the first and last item of the array

Suppose I have this array:
$array = array('10', '20', '30.30', '40', '50');
Questions:
What is the fastest/easiest way to remove the first item from the above array?
What is the fastest/easiest way to remove the last item from the above array?
So the resulting array contains only these values:
'20'
'30.30'
'40'
Using array_slice is simplest
$newarray = array_slice($array, 1, -1);
If the input array has less than 3 elements in it, the output array will be empty.
To remove the first element, use array_shift, to remove last element, use array_pop:
<?php
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
array_pop($array); // remove the last element
array_shift($array); // remove the first element
array_slice is going to be the fastest since it's a single function call.
You use it like this:
array_slice($input, 1, -1);
Make sure that the array has at least 2 items in it before doing this, though.
Check this code:
$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
Removes the first element from the array, and returns it:
array_shift($array);
Removes the last element from the array, and returns it:
array_pop($array);
If you dont mind doing them both at the same time, you can use:
array_shift($array,1,-1));
to knock off the first and last element at the same time.
Check the array_push, array_pop and array_slice documentation :)
<?php
$array = array("khan","jan","ban","man","le");
$sizeof_array = sizeof($array);
$last_itme = $sizeof_array-1;
//$slicearray= array_slice($array,'-'.$sizeof_array,4);// THIS WILL REMOVE LAST ITME OF ARRAY
$slicearray = array_slice($array,'-'.$last_itme);//THIS WILL REMOVE FIRST ITEM OF ARRAY
foreach($slicearray as $key=>$value)
{
echo $value;
echo "<br>";
}
?>

PHP: What is the fastest and easiest way to get the last item of an array?

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

Categories