Jump to content


Get Extension


5 replies to this topic

#1 Ziggy

    Young Padawan

  • Members
  • Pip
  • 14 posts

Posted 02 June 2007 - 12:22 PM

i am tring to get the extension of a file and here is my code so far
function ext($file){
	$a = explode(".", $file);
	$b = count($a);
	$ext = $a[$b];
	return $ext;
}

the problem is that it wont output the extension!

Edited by Ziggy, 02 June 2007 - 12:23 PM.


#2 Matthew.

    Official Spammer .Matt

  • Members
  • PipPipPipPip
  • 2,749 posts
  • Gender:Male
  • Location:England

Posted 02 June 2007 - 12:38 PM

You've missed something I myself have done before. Remember numeric arrays start with 0, not 1 as the value returned by count will do. Basically that means it is looking for an array element that does not exist.

All this means is we need to change this line:
$ext = $a[$b];

To this:
$ext = $a[($b - 1)];

You could also do:
return $a[count($a)-1];

Matt

Edited by Matthew., 02 June 2007 - 12:41 PM.


#3 Av-

    I Feel Left Out

  • Members
  • PipPipPipPip
  • 1,971 posts
  • Gender:Male
  • Location:10 ft. below sea level

Posted 02 June 2007 - 12:39 PM

hmm, try this instead

function ext($file){
	$a = array_reverse(explode(".", $file));
	return $a[0];
}

Given that the extension is always at the end, if your reverse the array, it will be the first key

edit: Matt beat me to it :laugh:

Edited by Av-, 02 June 2007 - 12:39 PM.


#4 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 02 June 2007 - 01:35 PM

Or better yet, don't create a custom function, but use a built in one...

pathinfo().

#5 Matthew.

    Official Spammer .Matt

  • Members
  • PipPipPipPip
  • 2,749 posts
  • Gender:Male
  • Location:England

Posted 02 June 2007 - 01:56 PM

View Postrc69, on Jun 2 2007, 07:35 PM, said:

Or better yet, don't create a custom function, but use a built in one...

pathinfo().

Damn your book like knowledge. Thanks rc, didn't know about that.

#6 Ziggy

    Young Padawan

  • Members
  • Pip
  • 14 posts

Posted 02 June 2007 - 04:24 PM

thanks guys





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users