Get all elements in array besides the first one.. ? (php) - php

Is there a way to specify getting all but the first element in an array? I generally use foreach() to loop through my arrays.
say array(1,2,3,4,5), i would only want 2, 3, 4 ,5 to show and for it to skip 1.

$arr = array(1,2,3,4,5);
$all_but_the_first_element_array = array_slice($arr, 1);

There are multiple ways of approaching this problem.
The first solution is to use a flag boolean to indicate the first element and proceed in your foreach
$firstElement = true;
foreach($array as $key => $val) {
if($firstElement) {
$firstElement = false;
} else {
echo "$key => $val\n";
}
}
If your elements are naturally numerically indexed, you do not need the boolean flag, you can simply check if the key is 0.
foreach($array as $key => $val) {
if($key === 0) continue;
echo "$key => $val\n";
}
The second way is to cheat your way into a naturally numerically indexed array if it isn't already. I will use array_keys() to get a naturally numerically indexed array of keys and loop it.
$keys = array_keys($array);
foreach($keys as $index => $key) {
if($index === 0) continue;
$val = $array[$key];
echo "$key => $val\n";
}
The third way is to use the array internal pointer to skip the first element and then continue in a loop by using reset(), next(), list(), and each(). Performance and resource-wise, this is the best option. Maintainability suffers greatly though.
reset($array); // Reset pointer to 0
next($array); // Advance pointer to 1
while (list($key, $val) = each($array)) {
echo "$key => $val\n";
}
If you don't mind losing the first element of the array, you can array_shift() it.
array_shift($array);
foreach($array as $key => $val) {
echo "$key => $val\n";
}
You can also array_slice() the array. I'm also using count() in order to be able to set the preserve_keys parameter to true.
$sliced = array_slice($array, 1, count($array)-1, true);
foreach($sliced as $key => $val) {
echo "$key => $val\n";
}

array_shift()
http://us2.php.net/manual/en/function.array-shift.php
example used in the site:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
The above example will output:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
**remember that the pointer to the array is reset (new value) after the shift

Well, there can be many ways for that as we have great deal of array-manipulation functions available. However i use the following method for that:
$orig_array = array(1, 2, 3, 4 ,5);
array_shift($orig_array);
print_r($orig_array);

Related

PHP filtering an associative array based on a value found in a subarray [duplicate]

I have an array like this:
array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.
So my expected result array would be:
array("a" => 2, "c" => 2, "f" => 2)
Note: I want to keep the keys from the original array.
How can I do that with PHP? Any built-in functions?
$fullArray = array('a'=>2,'b'=>4,'c'=>2,'d'=>5,'e'=>6,'f'=>2);
function filterArray($value){
return ($value == 2);
}
$filteredArray = array_filter($fullArray, 'filterArray');
foreach($filteredArray as $k => $v){
echo "$k = $v";
}
You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.
Loops while / for / foreach method
Loop through your array with any loop you want, may it be while, for or foreach. Then simply check for your condition and either unset() the elements if they don't meet your condition or write the elements, which meet the condition, into a new array.
Looping
//while loop
while(list($key, $value) = each($array)){
//condition
}
//for loop
$keys = array_keys($array);
for($counter = 0, $length = count($array); $counter < $length; $counter++){
$key = $keys[$counter];
$value = $array[$key];
//condition
}
//foreach loop
foreach($array as $key => $value){
//condition
}
Condition
Just place your condition into the loop where the comment //condition is. The condition can just check for whatever you want and then you can either unset() the elements which don't meet your condition, and reindex the array with array_values() if you want, or write the elements in a new array which meet the condition.
//Pseudo code
//Use one of the two ways
if(condition){ //1. Condition fulfilled
$newArray[ ] = $value;
//↑ Put '$key' there, if you want to keep the original keys
//Result array is: $newArray
} else { //2. Condition NOT fulfilled
unset($array[$key]);
//Use array_values() after the loop if you want to reindex the array
//Result array is: $array
}
array_filter() method
Another method is to use the array_filter() built-in function. It generally works pretty much the same as the method with a simple loop.
You just need to return TRUE if you want to keep the element in the array and FALSE if you want to drop the element out of the result array.
//Anonymous function
$newArray = array_filter($array, function($value, $key){
//condition
}, ARRAY_FILTER_USE_BOTH);
//Function name passed as string
function filter($value, $key){
//condition
}
$newArray = array_filter($array, "filter", ARRAY_FILTER_USE_BOTH);
//'create_function()', NOT recommended
$newArray = array_filter($array, create_function('$value, $key', '/* condition */'), ARRAY_FILTER_USE_BOTH);
preg_grep() method
preg_grep() is similar to array_filter() just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.
Also note that you can pass the flag PREG_GREP_INVERT as third parameter to invert the results.
//Filter by values
$newArray = preg_grep("/regex/", $array);
Common conditions
There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here:
//Odd values
return $value & 1;
//Even values
return !($value & 1);
//NOT null values
return !is_null($value);
//NOT 0 values
return $value !== 0;
//Contain certain value values
return strpos($value, $needle) !== FALSE; //Use 'use($needle)' to get the var into scope
//Contain certain substring at position values
return substr($value, $position, $length) === $subString;
//NOT 'empty'(link) values
array_filter($array); //Leave out the callback parameter
You can iterate on the copies of the keys to be able to use unset() in the loop:
foreach (array_keys($array) as $key) {
if ($array[$key] != 2) {
unset($array[$key]);
}
}
The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.
EDIT I just noticed, that you actually only need the keys that have a value of 2 (you already know the value):
$keys = array();
foreach ($array as $key => $value) {
if ($value == 2) {
$keys[] = $key;
}
}
This should work, but I'm not sure how efficient it is as you probably end up copying a lot of data.
$newArray = array_intersect_key(
$fullarray,
array_flip(array_keys($fullarray, 2))
);
This can be handled using a closure. The following answer is inspired by PHP The Right Way:
//This will create an anonymous function that will filter the items in the array by the value supplied
function cb_equal_to($val)
{
return function($item) use ($val) {
return $item == $val;
};
}
$input = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
// Use array_filter on a input with a selected filter function
$filtered_array = array_filter($input, cb_equal_to(2));
Contents of $filtered_array would now be
array ( ["a"] => 2 ["c"] => 2 ["f"] => 2 )
I think the snappiest, readable built-in function is: array_intersect()
Code: (Demo)
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
var_export(array_intersect($array, [2]));
Output:
array (
'a' => 2,
'c' => 2,
'f' => 2,
)
Just make sure you declare the 2nd parameter as an array because that is the value type expected.
Now there is nothing wrong with writing out a foreach loop, or using array_filter(), they just have a more verbose syntax.
array_intersect() is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.
From PHP7.4, arrow function syntax is available. This affords more concise code and the ability to access global variables without use.
Code: (Demo)
$haystack = [
"a" => 2,
"b" => 4,
"c" => 2,
"d" => 5,
"e" => 6,
"f" => 2
];
$needle = 2;
var_export(
array_filter(
$haystack,
fn($v) => $v === $needle
)
);
I might do something like:
$newarray = array();
foreach ($jsonarray as $testelement){
if ($testelement == 2){$newarray[]=$testelement}
}
$result = count($newarray);
foreach ($aray as $key => $value) {
if (2 != $value) {
unset($array($key));
}
}
echo 'Items in array:' . count($array);
You can do something like:
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
$arrayFiltered = array_filter($array, function ($element) {
return $element == 2;
});
or:
$arrayFiltered = array_filter($array, fn($element) => $element == 2);

How to PHP Unset Array Value [duplicate]

I have an array like this:
array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)
Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.
So my expected result array would be:
array("a" => 2, "c" => 2, "f" => 2)
Note: I want to keep the keys from the original array.
How can I do that with PHP? Any built-in functions?
$fullArray = array('a'=>2,'b'=>4,'c'=>2,'d'=>5,'e'=>6,'f'=>2);
function filterArray($value){
return ($value == 2);
}
$filteredArray = array_filter($fullArray, 'filterArray');
foreach($filteredArray as $k => $v){
echo "$k = $v";
}
You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.
Loops while / for / foreach method
Loop through your array with any loop you want, may it be while, for or foreach. Then simply check for your condition and either unset() the elements if they don't meet your condition or write the elements, which meet the condition, into a new array.
Looping
//while loop
while(list($key, $value) = each($array)){
//condition
}
//for loop
$keys = array_keys($array);
for($counter = 0, $length = count($array); $counter < $length; $counter++){
$key = $keys[$counter];
$value = $array[$key];
//condition
}
//foreach loop
foreach($array as $key => $value){
//condition
}
Condition
Just place your condition into the loop where the comment //condition is. The condition can just check for whatever you want and then you can either unset() the elements which don't meet your condition, and reindex the array with array_values() if you want, or write the elements in a new array which meet the condition.
//Pseudo code
//Use one of the two ways
if(condition){ //1. Condition fulfilled
$newArray[ ] = $value;
//↑ Put '$key' there, if you want to keep the original keys
//Result array is: $newArray
} else { //2. Condition NOT fulfilled
unset($array[$key]);
//Use array_values() after the loop if you want to reindex the array
//Result array is: $array
}
array_filter() method
Another method is to use the array_filter() built-in function. It generally works pretty much the same as the method with a simple loop.
You just need to return TRUE if you want to keep the element in the array and FALSE if you want to drop the element out of the result array.
//Anonymous function
$newArray = array_filter($array, function($value, $key){
//condition
}, ARRAY_FILTER_USE_BOTH);
//Function name passed as string
function filter($value, $key){
//condition
}
$newArray = array_filter($array, "filter", ARRAY_FILTER_USE_BOTH);
//'create_function()', NOT recommended
$newArray = array_filter($array, create_function('$value, $key', '/* condition */'), ARRAY_FILTER_USE_BOTH);
preg_grep() method
preg_grep() is similar to array_filter() just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.
Also note that you can pass the flag PREG_GREP_INVERT as third parameter to invert the results.
//Filter by values
$newArray = preg_grep("/regex/", $array);
Common conditions
There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here:
//Odd values
return $value & 1;
//Even values
return !($value & 1);
//NOT null values
return !is_null($value);
//NOT 0 values
return $value !== 0;
//Contain certain value values
return strpos($value, $needle) !== FALSE; //Use 'use($needle)' to get the var into scope
//Contain certain substring at position values
return substr($value, $position, $length) === $subString;
//NOT 'empty'(link) values
array_filter($array); //Leave out the callback parameter
You can iterate on the copies of the keys to be able to use unset() in the loop:
foreach (array_keys($array) as $key) {
if ($array[$key] != 2) {
unset($array[$key]);
}
}
The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.
EDIT I just noticed, that you actually only need the keys that have a value of 2 (you already know the value):
$keys = array();
foreach ($array as $key => $value) {
if ($value == 2) {
$keys[] = $key;
}
}
This should work, but I'm not sure how efficient it is as you probably end up copying a lot of data.
$newArray = array_intersect_key(
$fullarray,
array_flip(array_keys($fullarray, 2))
);
This can be handled using a closure. The following answer is inspired by PHP The Right Way:
//This will create an anonymous function that will filter the items in the array by the value supplied
function cb_equal_to($val)
{
return function($item) use ($val) {
return $item == $val;
};
}
$input = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
// Use array_filter on a input with a selected filter function
$filtered_array = array_filter($input, cb_equal_to(2));
Contents of $filtered_array would now be
array ( ["a"] => 2 ["c"] => 2 ["f"] => 2 )
I think the snappiest, readable built-in function is: array_intersect()
Code: (Demo)
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
var_export(array_intersect($array, [2]));
Output:
array (
'a' => 2,
'c' => 2,
'f' => 2,
)
Just make sure you declare the 2nd parameter as an array because that is the value type expected.
Now there is nothing wrong with writing out a foreach loop, or using array_filter(), they just have a more verbose syntax.
array_intersect() is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.
From PHP7.4, arrow function syntax is available. This affords more concise code and the ability to access global variables without use.
Code: (Demo)
$haystack = [
"a" => 2,
"b" => 4,
"c" => 2,
"d" => 5,
"e" => 6,
"f" => 2
];
$needle = 2;
var_export(
array_filter(
$haystack,
fn($v) => $v === $needle
)
);
I might do something like:
$newarray = array();
foreach ($jsonarray as $testelement){
if ($testelement == 2){$newarray[]=$testelement}
}
$result = count($newarray);
foreach ($aray as $key => $value) {
if (2 != $value) {
unset($array($key));
}
}
echo 'Items in array:' . count($array);
You can do something like:
$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
$arrayFiltered = array_filter($array, function ($element) {
return $element == 2;
});
or:
$arrayFiltered = array_filter($array, fn($element) => $element == 2);

Search array by values and return keys

I have values passed c and 3 from $_GET variable, which I want to look up in an array as values and retrieve their keys. How can I search through the array to return accurate keys?
The code below
<?php
$array1 = array(0 => 'a', 1 => 'c', 2 => 'c');
$array2 = array(0 => '3', 1 => '2', 2 => '3');
$key1 = array_search('c', $array1);
$key2 = array_search('3', $array2);
?>
returns
$key1 = 1;
$key2 = 0;
though I am expecting
$key1 = 2;
$key2 = 2;
foreach ($array1 as $key => $value) {
if ($value == 'c' && $array2[$key] == '3') {
echo "The key you are looking for is $key";
break;
}
}
I'm pretty sure there's a saner way to do whatever you're trying to do though.
The function returned exactly as it should have. The first occurrence of value 'c' exists at index 1 in $array1 and the value '3' has its first occurrence at index 0 in $array2
This behavior is documented in the php docs on array_search and it even supplies you with an alternative if you don't like it:
If needle is found in haystack more than once, the first matching key
is returned. To return the keys for all matching values, use
array_keys() with the optional search_value parameter instead.
If you want to find the last key that has that value, you could reverse your array first.
$array1 = array(0 => 'a', 1 => 'c', 2 => 'c');
$array2 = array(0 => '3', 1 => '2', 2 => '3');
$key1 = array_search('c', $array1);
$key2 = array_search('3', $array2);
var_dump($key1,$key2); //output: int(1) int(0)
$key1 = array_search('c', array_reverse($array1, true));
$key2 = array_search('3', array_reverse($array2, true));
var_dump($key1,$key2); //output: int(2) int(2)
Perhaps something like:
<?php
// for specificly 2 arrays
function search_matching($match1, $match2, array $array1, array $array2) {
foreach($array1 as $key1 => $value1) {
// we may want to add $strict = false argument to distinguish between == and === match
// see http://php.net/manual/en/function.array-search.php
if($value1 == $match1 and isset($array2[$key1]) and $array2[$key1] == $match2) {
return $key1;
}
}
return null;
}
// unlimited
function search_matching(array($matches), array $array/*, ...*/) {
if( count($matches) != func_num_args() - 1)
throw new \Exception("Number of values to match must be the same as the number of supplied arrays");
$arrays = func_get_args();
array_shift($arrays); // remove $matches
$array = array_unshift($arrays); // array to be iterated
foreach($array as $key => $value) {
if($value == $matches[0]) {
$matches = true;
foreach($arrays as $keyA => $valueA) {
if(! isset($arrays[$key] or $valueA != $matches[$keyA+1]) {
$matches = false;
break;
}
}
if($matches)
return $key;
}
}
return null;
}
The functions are created with numerical keys in mind.
They could be made cleaner by offloading some functionality to other function, but I wanted to keep it concise and together for the sake of easily seeing how it works

Merge and group by several arrays

I need to merge associative arrays and group by the name. Say I have such 3 arrays:
ARRAY1
"/path/file.jpg" => 2,
"/path/file2.bmp" => 1,
"/file3.gif" => 5,
ARRAY2
"/path/file.jpg" => 1,
"/path/file2.bmp" => 1,
"/file3.gif" => 0,
ARRAY3
"/path/file.jpg" => 1,
"/path/file2.bmp" => 1,
I need to merge these arrays to one and group them by filepath and have result of sum of their values. Something like:
SELECT filename, SUM(val) FROM files
GROUP BY filename
But with multiple input arrays. Arrays are short (around 20 elements max). Each array might have different size.
[EDIT: I adapted the function (as suggested by John Green) to use func_get_args so you don't need to put all the seperate arrays in one array before you can use it.]
I think you could use the following function.
mergeArrays()
{
$return = array();
$arrays = func_get_args();
foreach ($arrays as $array) {
foreach ($array as $key => $val) {
if (array_key_exists($key, $array) {
$return[$key] += $val;
} else {
$return[$key] = $val;
}
}
}
return $return;
}
one possible way
$rtn = array();
foreach ($array1 as $key=>$val)
{
$rtn[$key]+=$val;
}
foreach ($array2 as $key=>$val)
{
$rtn[$key]+=$val;
}
foreach ($array2 as $key=>$val)
{
$rtn[$key]+=$val;
}
the above will assign the filename, SUM(val) as an associative array into $rtn
You can use a RecursiveArrayIterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($paths));
foreach ($iterator as $path => $value) {
$summed[$path] = isset($summed[$path]) ? $summed[$path] + $value : $value;
}
print_r($summed);
or array_walk_recursive and a Closure
$summed = array();
array_walk_recursive($paths, function($value, $path) use (&$summed) {
$summed[$path] = isset($summed[$path]) ? $summed[$path] + $value : $value;
});
Both will give
Array
(
[/path/file.jpg] => 4
[/path/file2.bmp] => 3
[/file3.gif] => 5
)

Checking during array iteration, if the current element is the last element

Please help me to translate this pseudo-code to real php code:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
Edit: the array may have numerical or string keys
you can use PHP's end()
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
Update1
as pointed out by #Mijoja the above could will have problem if you have same value multiple times in array. below is the fix for it.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
if($k == $lastElementKey) {
//during array iteration this condition states the last element.
}
}
Update2
I found solution by #onteria_ to be better then what i have answered since it does not modify arrays internal pointer, i am updating the answer to match his answer.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
if($k == $lastArrayKey) {
//during array iteration this condition states the last element.
}
}
Thank you #onteria_
Update3
As pointed by #CGundlach PHP 7.3 introduced array_key_last which seems much better option if you are using PHP >= 7.3
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastKey = array_key_last($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($k == $lastKey) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
This always does the trick for me
foreach($array as $key => $value) {
if (end(array_keys($array)) == $key)
// Last key reached
}
Edit 30/04/15
$last_key = end(array_keys($array));
reset($array);
foreach($array as $key => $value) {
if ( $key == $last_key)
// Last key reached
}
To avoid the E_STRICT warning mentioned by #Warren Sergent
$array_keys = array_keys($array);
$last_key = end($array_keys);
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Since array_pop works on the temporary array created by array_keys it doesn't modify the original array at all.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
Why not this very simple method:
$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
$i++;
if( $i == sizeof($array) ){
//we are at the last element of the array
}
}
I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:
$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
// just to use this `hasNext()` method to see
// if this is the last element
echo $each;
}
}
My solution, also quite simple..
$array = [...];
$last = count($array) - 1;
foreach($array as $index => $value)
{
if($index == $last)
// this is last array
else
// this is not last array
}
If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:
$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
$v = current($arr); doSomething($v); //do something if not the last item
next($myArray); //set pointer to next item
}
Simple approach using array_keys function to get the keys and get only first key [0] of reversed array which is the last key.
$array = array('a' => 1,'b' => 2,'c' => 3);
$last_key = array_keys(array_reverse($array, true))[0];
foreach($array as $key => $value) {
if ($last_key !== $key)
// THIS IS NOT THE LAST ELEMENT IN THE ARRAY doSomething();
}
NOTE: array_reverse reverse array take two arguments first array we want be reversed and second parameter true, to reverse the array and preserves the order of keys.

Categories