What is $variable[count($variable)-1] Doing?
It's a s开发者_如何转开发imple 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];
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)]
.
$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.
$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.
精彩评论