tags:

views:

422

answers:

9
$array = explode(".", $row[copy]);
$a = $array.length -1;

I want to return the last element of this array but all i get from this is -1. Help would be much appreciated.

A: 

I think your second line should be more like:

$index = count($array) - 1;
$a = $array[$index];

If you want an element from an array you need to use square brackets.

benzado
PHP doesn't have a length() function.
yjerem
Thanks, I get that wrong every time.
benzado
+7  A: 

Try count:

$array = explode(".", $row[copy]);
$a = count($array) - 1;
$array[$a]; // last element
Jonathan Lonowski
A: 

My PHP is a bit rusty, but shouldn't this be:

$array = explode(".", $row[$copy]);
$a = $array[count($array)];

i.e.: isn't a "$" missing in front of "copy", and does .length actually work?

Rick
A: 

As this is tag as PHP, I'll assume you are using PHP, if so then you'll want to do:

$array = explode(".", $row[copy]);
$a = count($array) - 1;
$value = $array[$a];

But this will only work if your keys are numeric and starting at 0.

If you want to get the last element of an array, but don't have numeric keys or they don't start at 0, then:

$array = explode(".", $row[copy]); $revArray = array_reverse($array, true); $value = $revArray[key($revArray)];

Darryl Hein
+3  A: 

You could also use array_pop(). This function takes an array, removes the last element of the array and returns that element.

$array = explode(".", $row[copy]);
$a = array_pop($array);

This will modify the $array, removing the last element, so don't use it if you still need the array for something.

yjerem
+9  A: 

You can also use:

$a = end($array);

This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.

+1  A: 

If you just want everythng after the final . you could try

$pos = strrpos($row['copy'], '.');
$str=($pos!==false) ? substr($row['copy'],$pos+1) : '';

This saves generating an array if all you needed was the last element.

Paul Dixon
+1  A: 

Actually, there is a function that does exactly what you want: end()

$res = end( explode('.', $row['copy']) );

A: 

hi u can use this also :

$stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack);

After this, $stack will have only 3 elements:

Array ( [0] => orange [1] => banana [2] => apple )

and raspberry will be assigned to $fruit.