There is an array, the count of the element is unknown,like this:
$arr=['a','m','q','y',....'b','f','n','s'];
How to get the second-to-last element in PHP?
You can use array_slice() like this:
<?php
$arr=['a','m','q','y','b','f','n','s'];
echo array_slice($arr, -2, 1)[0];
Output:
n
Note: this will work regardless of the array type: indexed or associative. So even if the keys are not 0, 1, 2, 3, etc... then this would still work.
Since there are no defined keys, it's a little easier:
$second_to_last = $arr[count($arr) - 3];
I think this is the answer;
$arr[count($arr)-3]
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.
Quick PHP problem here :
When doing a for each statement I have to echo it in a perticular syntax I.E
|First_Name:bob,jim,alex,gary|Last_Name:Smith,Doe,foo|Age:11,12,13
I have so far manage to achieve this syntax except for the last value of each of the for loop as I get this result
|First_Name:bob,jim,alex,gary,|Last_Name:Smith,Doe,foo,|Age:11,12,13,
so the is an extra comma in every itteration of the second loop.
Is there a way to get rid of the comma for the last value only.
Try this:
$abc = "First_Name:bob,jim,alex,gary,";
$rest = substr($abc, -1);
There is a built-in function for joining array elements, called implode, which I suggest you should use:
$a = [1, 2, 3];
$s = implode(",", $a);
// result: "1,2,3"
NB: The short array notation was introduced in PHP 5.4. For older versions, use this line instead to initialize an array:
$a = array(1, 2, 3);
Say I have a multi-dimensional array set up as follows:
$matrix[1][1]=4.54; $matrix[2][1]="apples"; $matrix[3][1]="coles";
$matrix[1][2]=7.2140230; $matrix[2][2]="apples"; $matrix[3][2]="safeway";
$matrix[1][3]=15.56; $matrix[2][3]="oranges"; $matrix[3][3]="coles";
$matrix[1][4]=2.34; $matrix[2][4]="bananas"; $matrix[3][4]="safeway";
$matrix[1][5]=27.98; $matrix[2][5]="grapes"; $matrix[3][5]="coles";
$matrix[1][6]=17.68493403; $matrix[2][6]="oranges"; $matrix[3][6]="safeway";
And I wish to re-arrange by the pricing information which I've stored under the first 1st column, so that the new order of $matrix would be:
$matrix[1][1]=2.34; $matrix[2][1]="bananas"; $matrix[3][1]="safeway";
$matrix[1][2]=4.54; $matrix[2][2]="apples"; $matrix[3][2]="coles";
$matrix[1][3]=7.2140230; $matrix[2][3]="apples"; $matrix[3][3]="safeway";
$matrix[1][4]=15.56; $matrix[2][4]="oranges"; $matrix[3][4]="coles";
$matrix[1][5]=17.68493403; $matrix[2][5]="oranges"; $matrix[3][5]="safeway";
$matrix[1][6]=27.98; $matrix[2][6]="grapes"; $matrix[3][6]="coles";
What would be the best way to achieve this? I've read other questions about sorting multi-dimensional arrays but have had trouble implementing because those examples seemed to have associative arrays with keys and elements, whereas I am just using the different numbers to store each piece of data. I would prefer not to change the way I am storing data in the array as the actual script is quite long and complex and so this would involve a lot of re-work.
I am completely new to PHP so my apologies if I am missing something obvious here. Thanks for your help.
EDIT: Thanks everyone for your advice, scessors code is exactly what I needed. Halfer - to your 1st question - Yes, 2nd post - good point, I will implement this. Thanks again everyone!
If it's no problem that the sorted array begins with zero, you can use array_multisort:
array_multisort(
$matrix[1], SORT_ASC, SORT_NUMERIC,
$matrix[2], SORT_ASC, SORT_STRING,
$matrix[3], SORT_ASC, SORT_STRING
);
Also see my example.
I believe that phps array_multisort will do it for you:
Heres an example from docs:
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>
In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.
From: http://php.net/manual/en/function.array-multisort.php
Using my_uksort provided by Adam Backstrom
<?php
function my_uksort($a, $b) {
global $matrix;
asort($matrix[1]);
return $matrix[1][$a] < $matrix[1][$b] ? -1 : 1;
}
uksort($matrix[2], 'my_uksort');
uksort($matrix[3], 'my_uksort');
print_r($matrix);
?>
DEMO
I have a range of 67 numbers, something like 256 through to 323, which I want to add to an existing array. it doesn't matter what the values are.
looking for code to iterate through those numbers to add them as keys to the array without adding each one at a time
Try array_fill_keys and range
$existingArray = array('foo', 'bar', 'baz');
$existingArray += array_fill_keys(range(256,323), null);
Use whatever you like instead of null. You could also use array_flip() instead of array_fill_keys(). You'd get the index keys as values then, e.g. 256 => 1, 257 => 2, etc.
Alternatively, use array_merge instead of the + operator. Depends on the outcome you want.
you can use range() eg range(256,323)
push(); could be a look worth, or you can do it
like this
for($i=0;$i<count($array);$i++)
{
$anotherArray[$i] = $array[$i];
}
You can try using the range and array_merge functions.
Something like:
<?php
$arr = array(1,2,3); // existing array.
$new_ele = range(256,323);
// add the new elements to the array.
$arr= array_merge($arr,$new_ele);
var_dump($arr);
?>
If I have this array:
<?php
$array[0]='foo';
$array[1]='bar';
$array[2]='foo2';
$array[3]='bar3';
?>
And I want to delete the second entry ($array[1]), but so that all the remaining entries' indexes automatically get adjusted, so the next 2 elements whose indexes are 2 and 3, become 1 and 2.
How can this be done, or is there any built in function for this?
There are several ways to do that. One is to use array_values after deleting the item to get just the values:
unset($array[1]);
$array = array_values($array);
var_dump($array);
Another is to use array_splice:
array_splice($array, 1, 1);
var_dump($array);
You can use array_splice(). Note that this modifies the passed array rather than returning a changed copy. For example:
$array[0] = 'foo';
//etc.
array_splice($array, 1, 1);
print_r($array);
I always use array_merge with a single array
$array = array_merge($array);
print_r($array);
from php.net:
http://us.php.net/array_merge
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.