tags:

views:

68

answers:

3

It's a simple question, but no matter where I look, I can't seem to figure out how it works. I believe it's taking the first character off the beginning of $variable, but how does count($variable)-1 do this?

$variable[count($variable)-1]

Full code:

$fileType  = explode('.',$_FILES['Filedata']['name']);
$fileName = str_ireplace('.jpg', '', $_FILES['Filedata']['name']);
$targetFile =  str_replace('//','/',$targetPath) . $fileName .'.'.$fileType[count($fileType)-1];
+1  A: 

$fileType is an array, split on the period character, from a string corresponding to a file name. The count() bit gives you the number of elements in the array. It's returning the last element from the zero-based array, which is the file extension.

tvanfosson
+5  A: 

count($variable) returns the number of elements in an array, but array indices in PHP are zero-based: that is, a 10 element array has elements with indices 0-9.

So, $variable[count($variable) - 1] gets the last element in the array.

Although, this could've been done with end(): end($variable) == $variable[count($variable-1)].

Mark Trapp
Ahh yes. It seems to obvious now. I forgot the variable name was carried from the exploded array. Thanks!
gamerzfuse
A: 

$variable is an array. The count function in PHP counts the number of elements in the array. In PHP and other programming languages, the first element index is zero and the last element index is N - 1 for an array of N size.

So $variable[count($variable)-1] will return the last value of the array.

Dimitri