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
Related
I wanted to test array_shift on a simple example:
$a = ['a', 'b', 'c', 'd'];
$rem = array_shift($a);
print_r($rem);
Which only returns me: a, instead of an array of: ['b', 'c', 'd'].
php.net docs on array_shift state the following:
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.
This function is supposed to remove the first element and return all the rest with re-ordered keys.
Now, I copied the example from the docs site as is (tried with both [] and array()):
$stack = ["orange", "banana", "apple", "raspberry"];
$fruit = array_shift($stack);
print_r($stack);
Now this returns as expected:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
I don't understand what just happend here or what I did wrong.
My example only differs in variable names and elements in the array.
And I hardly don't believe the issue would be because of my usage of single-quotes '.
Also, here is a demo on Sandbox.
array_shift() is a stand-alone function - you don't need to assign it to a value, it automatically unsets it from the given variable:
<?php
$a = ['a', 'b', 'c', 'd'];
array_shift($a);
print_r($a);
https://3v4l.org/GEr3g
array_shift() shifts the first value of the array off and returns it
The "it" refers to "the first value", not to "the array". It shifts off the first value and returns said first value; the array is being shortened by that process. Pay close attention to what is being returned in the example code ($fruit) and what you print ($stack).
To leave the original array intact and return a new, shorter array, you'd do:
$rem = array_slice($a, 1);
In you example $rem is the return from the function array_shift as stated on the doc it will return the eliminated index value, on the other side whenever you print
print_r($a);
This will return the array after the function performed.
As the php doc array_shift shows.
The return result of array_shift is the first value of the array that been shifted off, and remove the first value of the original array.
array_shift ( array &$array ) : mixed
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.
This question already has answers here:
How do I create a comma-separated list from an array in PHP?
(11 answers)
Closed 2 years ago.
I'm trying to concatenate array keys (which are originally a class properties). So what I did is:
echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';
Outputs:
Array
(
[0] => streetAddress_1
[1] => street_address_2
[2] => city_name
[3] => subdivision_name
[4] => country_name
)
This is how I get the AddressPark object's properties names.
$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);
I want to access the object properties by index, that is why I used array_keys.
$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;
The results is:
streetAddress_1,streetAddress_1,streetAddress_1,country_name
It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0.
So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).
So is there another way to do it?
No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.
array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.
Implode
implode: Join array elements with a string
string implode ( string $glue , array $pieces )
Example:
<?php
$myArray = ['one','two','three'];
echo implode(',', $myArray);
// one,two,three
echo implode(' Mississippi;', $myArray);
// one Mississippi; two Mississippi; three Mississippi;
Foreach
foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.
foreach (array_expression as $key => $value)
...statement...
Example:
<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
$output .= $val . ',';
}
echo $output;
// one,two,three,
Notice that on this version we have an extra comma to deal with
<?php
echo rtrim($output, ',');
// one,two,three
List
list: Assign variables as if they were an array
array list ( mixed $var1 [, mixed $... ] )
Example:
<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three
Note that on this version you have to know how many values you want to deal with.
Array Reduce
array_reduce: Iteratively reduce the array to a single value using a callback function
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
Example:
<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
return $carry .= $item . ', ';
}, '');
// one, two, three,
This method also causes an extra comma to appear.
While
while: while loops are the simplest type of loop in PHP.
while (expr)
...statement...
Example:
<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
$output .= array_shift($myArray);
$output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three
Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.
Sprintf and String Repeat
sprintf: My best attempt of actually using the str_repeat function:
<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three
Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.
Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.
There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.
If you can think of any more post a comment below :-)
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
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).
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>";
}
?>