Up front, I would like to clarify that I am not looking for a workaround to find max--I already have the solution for accomplishing that goal. What I am curious about is why max(array_push()) doesn't work.
I have an array with many values in it, and want to find the max of specific values within that array. Existing array:
$array1 = array(2,6,1,'blue','desk chair');
The basic idea is to create a new array consisting of those specified values, and then find the max of that new array. I attempted to make this effort operate all on one line:
$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//this doesn't work at all, since $array2 doesn't already exist, as per the PHP manual
I changed to code to first create $array2, but didn't assign values at that time, just to see if the code works.
$array2 = array();
$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//$array2 is populated, but $max is not assigned
The obvious solution is to assign values to $array2 at creation and then use max() by itself. I'm just curious as to why max(array_push()) doesn't find max, since compounded functions normally operate from inside to outside.
Thank you.
max needs an array to work with but array_push returns an integer and actually uses the provided array by reference, you have to do :
$array2 = array();
array_push($array2, $array1[0], $array1[1], $array1[2])
$max = max($array2);
Alternatively do:
$array2 = array($array1[0], $array1[1], $array1[2]);
$max = max($array2);
A 3rd option (though not the cleanest one):
$array2 = array();
$max = max($array2 = array_merge($array2, [$array1[0], $array1[1], $array1[2]]));
For reference, see:
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.array-push.php
You could also use array_slice():
$max = max(array_slice(
$array1,
0,
3
));
if
the values you are interested in are in a sequence
you know offset and length of the sequence
For reference, see:
http://php.net/manual/de/function.array-slice.php
http://php.net/manual/de/function.max.php
For an example, see:
https://3v4l.org/nMK1Z
Related
if I give you:
$array = array(object1, object2, object3, object4);
and say, at position 2, remove all elements before this position so the end result is:
$array = array(object3, object4);
What would I do? I was looking at array_shift and array_splice to achieve what I wanted - how ever I am not sure which to use or how to use them to achieve the desired affect.
Use array_slice. For more detail check link http://php.net/manual/en/function.array-slice.php
$array = array(object1, object2, object3, object4);
$array = array_slice($array,2); // 2 is position
Or if you are looking into the values instead of the index, with a tiny adjustment in #Ashwani's answer you can have:
$array = array('object1', 'object2', 'object3', 'object4');
$slice = array_slice($array, array_search('object3',$array));
array_slice is one way to go about it, however, if you are wanting to remove all the elements in an any array before a specific value, without searching, then:
//assuming you've already verified the match is in the array
//make a copy of $array first if you don't want to break the original
while($array[0] !== $match) {
array_shift(&$array);
}
Alternatively, you could:
$index = array_search($match, array_values($array));
if($index !== false) $array = array_slice($array, $index);
This accomplished both the verification and slice. Note the array_values() is used to account for associative arrays.
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.
So I've got this:
$h = $user_goals;
while($h > 0) {
randomScorer();
$minute = rand(0,90);
echo "(".$minute.")<br>";
$h--;
Basically, what it does is, $user_goals, has a load of factors drawn into it and creates a number, between 0-5, and this information is used to generate the times of the goals, using the above PHP function.
It's working, it's brilliant, etc. However, the numbers are appearing in random order in which they are generated and so I was wondering:
Is there any way to sort these numbers?
Would I put them into an array during this iteration methodology, and then sort the array by the number's value?
Any help is greatly appreciated!
That is why PHP provides us Sort functions. Have a look here.
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
?>
Since your array is NUMERIC, you need to use the FLAG along with the sort function.
sort($goals, SORT_NUMERIC);
print_r($goals);
Same idea, using sort() but also uses range and array_walkto set up your array a little closer to how you already do it:
$goal_array = range(1, $user_goals); // Warning, assumes $user_goals is number
array_walk($goal_array, function(&$goal) {
randomScorer();
$goal = rand(0,90);
});
sort($goal_array, SORT_NUMERIC);
$index = 0;
foreach ($sxml->entry as $entry) {
$array + variable index number here = array('title' => $title);
$index++;
}
I'm trying to change an array name depending on my index count. Is it possible to change variable name (ie. $array1, $array2 $array3 etc.) in the loop?
Edit:
After the loop has finished, I will generate a number number (depending on the count of $index) and then use this array... probably it's a stupid way of accomplishing what Im trying to do, but I don't have a better idea.
You might want to try this instead:
$index = 0;
$arrays = array();
foreach ($sxml->entry as $entry) {
$arrays[$index] = array('title' => $title);
$index++;
}
While it is technically possible to do what you are asking, using an array of arrays will probably work better from you.
This type of indexing is exactly what arrays are designed for, you have a lot of items and want to be able to refer to them by number.
Unless you have a very specific reason to use the name of the variable to represent it's number you will probably have a much simpler time using it's index in the outer array.
Yes you can user an associate array. Generating a string dynamically based on the iteration number and using that as a key in the array.
You can use variable variables. php.net
PHP supports Variable variables:
$num = 1;
$array_name = 'array' . $num;
$$array_name = array(1,2,3);
print_r($array1);
http://php.net/manual/en/language.variables.variable.php
I'm frequently using the following to get the second to last value in an array:
$z=array_pop(array_slice($array,-2,1));
Am I missing a php function to do that in one go or is that the best I have?
end($array);
$z = prev($array);
This is more efficient than your solution because it relies on the array's internal pointer. Your solution does an uncessary copy of the array.
For numerically indexed, consecutive arrays, try $z = $array[count($array)-2];
Edit: For a more generic option, look at Artefecto's answer.
Or here, should work.
$reverse = array_reverse( $array );
$z = $reverse[1];
I'm using this, if i need it :)