I have an array that is structured like this:
[33] => Array
(
[time] => 1285571561
[user] => test0
)
[34] => Array
(
[time] => 1285571659
[user] => test1
)
[35] => Array
(
[time] => 1285571682
[user] => test2
)
How can I get the last value in the array, but maintaining the index [35]?
The outcome that I am looking for is this:
[35] => Array
(
[time] => 1285571682
[user] => test2
)
try to use
end($array);
$last = array_slice($array, -1, 1, true);
See http://php.net/array_slice for details on what the arguments mean.
P.S. Unlike the other answers, this one actually does what you want. :-)
You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:
$last = end($arr);
$last = current(array_slice($arr, -1));
If you have an array
$last_element = array_pop(array);
Example 1:
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(end($arr));
Output = e
Example 2:
ARRAY without key(s)
$arr = array("a", "b", "c", "d", "e");
print_r(array_slice($arr, -1, 1, true));
// output is = array( [4] => e )
Example 3:
ARRAY with key(s)
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
print_r(array_slice($arr, -1, 1, true));
// output is = array ( [lastkey] => e )
Example 4:
If your array keys like : [0] [1] [2] [3] [4] ... etc. You can use this:
$arr = array("a","b","c","d","e");
$lastindex = count($arr)-1;
print_r($lastindex);
Output = 4
Example 5:
But if you are not sure!
$arr = array("a"=>"a", "5"=>"b", "c", "key"=>"d", "lastkey"=>"e");
$ar_k = array_keys($arr);
$lastindex = $ar_k [ count($ar_k) - 1 ];
print_r($lastindex);
Output = lastkey
Resources:
https://php.net/array_slice
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/function.count.php
https://www.php.net/manual/en/function.end.php
Like said Gumbo,
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
Another solution cold be:
$value = $arr[count($arr) - 1];
The above will count the amount of array values, substract 1 and then return the value.
Note: This can only be used if your array keys are numeric.
As the key is needed, the accepted solution doesn't work.
This:
end($array);
return array(key($array) => array_pop($array));
will return exactly as the example in the question.
"SPL-way":
$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);
Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.
Related
Array
(
)
Array
(
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
[1] => 12
)
I want this array
Array
(
[0] => 14
[1] => 12
)
Here is my code:
$colorarray = array();
foreach($catIds as $catid){
$colorarray[] = $catid;
}
Need to get unique array values
Thanks
You can use call_user_func_array with array-merge for flatten your array and then use array-unique as:
$res = call_user_func_array('array_merge', $arr);
print_r(array_unique($res)); // will give 12 and 14
Live example 3v4l
Or as #Progrock suggested: $output = array_unique(array_merge(...$data)); (I like that syntax using the ...)
You can always do something like this:
$colorarray = array();
foreach($catIds as $catid){
if(!in_array($catid, $colorarray) {
$colorarray[] = $catid;
}
}
But also this has n*n complexity, So if your array is way too big, it might not be the most optimised solution for you.
You can do following to generate unique array.
array_unique($YOUR_ARRAY_VARIABLE, SORT_REGULAR);
this way only unique value is there in your array instead of duplication.
UPDATED
This is also one way to do same
<?php
// define array
$a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);
// print original array
echo "Original Array : \n";
print_r($a);
// remove duplicate values by using
// flipping keys and values
$a = array_flip($a);
// restore the array elements by again
// flipping keys and values.
$a = array_flip($a);
// re-order the array keys
$a= array_values($a);
// print updated array
echo "\nUpdated Array : \n ";
print_r($a);
?>
Reference link
Hope this will helps you
I have updated your code please check
$colorarray = array();
foreach($catIds as $catid){
$colorarray[$catid] = $catid;
}
This will give you 100% unique values.
PHP: Removes duplicate values from an array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
------your case--------
$result = array_unique($catIds);
print_r($result);
You can construct a new array of all values by looping through each sub-array of the original, and then filter the result with array_unique:
<?php
$data =
[
[
0=>13
],
[
0=>13
],
[
0=>17,
1=>19
]
];
foreach($data as $array)
foreach($array as $v)
$all_values[] = $v;
var_export($all_values);
$unique = array_unique($all_values);
var_export($unique);
Output:
array (
0 => 13,
1 => 13,
2 => 17,
3 => 19,
)array (
0 => 13,
2 => 17,
3 => 19,
)
I'm running a foreach loop on an array of students, that have a key ['all_user_grades']. What is the best way to count the number of As,Bs,Cs,Ds,Es and fails for each student in the array.
Here's what my array looks like:
[11] => Array
(
[id] => 10
[All_User_Grades] => A, A, D, A, E
)
Here's what my foreach looks like so far:
foreach($user_grades as $k => $v){
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
}
You can use the array_count_values() function:
$array = array('A', 'A', 'D', 'A', 'E');
$result = array_count_values($array);
print_r($result);
It outputs:
Array
(
[A] => 3
[D] => 1
[E] => 1
)
You can use substr_count() for this like so
$As = substr_count($aug, 'A');
$Bs = substr_count($aug, 'B');
//etc
or, just like you already did, explode and use the array for calculation
$all_user_grades_arr = explode(',', $aug);
$grades = array('A' => 0, 'B' => 0', ...);
foreach ($all_user_grades_arr as $val) {
$grades[ trim($val) ]++;
}
The trim() here is necessary to get rid of unnecessary whitespaces
You can try this way using array_count_values, i have used for single array, you change as per your requirements. See Demo http://ideone.com/YrGfPD
//PHP
$v=array('Id'=>10,'All_User_Grades'=>'A,A,D,A,E');
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
echo '<pre>';
print_r(array_count_values($all_user_grades_arr));
echo '</pre>';
//OUTPUT
Success time: 0.02 memory: 24448 signal:0
Array
(
[A] => 3
[D] => 1
[E] => 1
)
I have a very simple array like this:
Array ( [friend_id] => 180 [user_id] => 175 )
What I want to do is just to switch the values, in order to be come this:
Array ( [friend_id] => 175 [user_id] => 180 )
Is there any elegant NON STATIC way in PHP to do it?
you can use array_combine and array_reverse
$swapped = array_combine(array_keys($arr), array_reverse(array_values($arr)));
No. Use a temporary value:
$temp = $array['friend_id'];
$array['friend_id'] = $array['user_id'];
$array['user_id'] = $temp;
A bit longish, but I think it satisfies you requirements for 2 element arrays, just as you used in your example:
// your input array = $yourarray;
$keyarray = array_keys($yourarray);
$valuearray = array_values($yourarray);
/// empty input array just to make sure
$yourarray = array();
$yourarray[$keyarray[0]] = $valuearray[1];
$yourarray[$keyarray[1]] = $valuearray[0];
Basically Orangepill's answer done manually...
How about using array_flip?
array array_flip ( array $trans )
$myar = array('apples', 'oranges', 'pineaples'); print_r($myar);
print_r(array_flip($myar));
Array
(
[0] => apples
[1] => oranges
[2] => pineaples
)
Array
(
[apples] => 0
[oranges] => 1
[pineaples] => 2
)
$tmp = $array['user_id'];
$array['user_id'] = $array['friend_id'];
$array['friend_id'] = $tmp;
Is it possible to divide a number into an array based on its value?
For example:
$val = 3;
// do something here to convert the number 3 into 1's
Array
(
[0] => 1
[1] => 1
[2] => 1
)
$array = array_fill(0, $val, 1);
array_fill(0, $val, 1);
will create an array
Array
(
[0] => 1
[1] => 1
[2] => 1
)
Do something like this:
$arr = Array();
for ($i=0;$i<$val;$i++) {
$arr[] = 1;
}
But with larger numbers you may need something different.
Another slightly shorter solution is to use range()
$val = 3;
$array = range(1, $val);
print_r($array);
// Output:
// Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// )
It's not possible for the value to be negative, or zero.
That's good, because all of these solutions (including loops) won't work with a zero or negative. However, range() will give you a different result (the 5 digit range of 1 to -3, for example).
How do I access the following array in PHP:
$Record = Array ( [0] => 1 [1] => 1 [2] => 1);
I have tried
echo $Record[0];
But no luck :(
To initialize an array (you don't need an associative array, if your keys are just the actual indices) use:
$record = array(1, 1, 1);
Then you can access the first element via:
$first = $record[0];
Try
$Record = array( 0 => 1, 1 => 1, 2 => 1);
or even
$Record = array(1,1,1);
and then
echo $Record[0];
Keep in mind that print_r shows you some form of representation of the array. so this code:
$record1 = array(1,1,1);
print_r($record1);
will output:
Array
(
[0] => 1
[1] => 1
[2] => 1
)
$Record = Array ( 1, 1, 1 );
your array has wrong syntax
just a guess, but you can try something like that:
$pattern = "|\[(\d+)\] => (\d+)|";
preg_replace_callback(
$pattern,
"add_to_array",
$text);
and write a function 'add_to_array' to add to your array, get the index by $matches[1] and the value by $matches[2]!