Web Analytics Made Easy -
StatCounter My function is not returning any value - CodingForum

Announcement

Collapse
No announcement yet.

My function is not returning any value

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • My function is not returning any value

    Hi,
    I am trying to check file extension. For this I have created a function but it is not returning any value. I really can't figure out where I am wrong. Below is the code :

    function checkType($name){
    $farray = explode('.',$name);
    $fname = trim($farray[0]);
    $fext = trim($farray[1]);
    echo $fext; <---- Here the value is showing.
    return $fext;
    }

    Code from I am calling this function is :

    $filename = "IMG_3552.JPG"
    echo $filename;
    checkType($filename);
    echo "File Extension is : ". $fext;

    ------------------------------------------
    Echoed valued is shown below :

    IMG_3552.JPG

    File Extension is :

    Please help ??

  • #2
    You're not assigning the result to anything. $fext is a local variable inside the function, it does not exist outside the function. When you "return' a value it's the result of the function, it does NOT expose the variable's scope outside it.

    echo 'File Extension is : ', checkType($filename);

    Will output the result. As would:

    $type = checkType($filename);
    echo 'File Extension is : ', $type;

    On the receiving end you have to assign that returned value to something or use it right away.
    Walk the dark path, sleep with angels, call the past for help.
    https://cutcodedown.com
    https://medium.com/@deathshadow

    Comment


    • #3
      An improvement would be to use the built in mime_content_type() function that checks the MIME type of the file rather than the extension (which can easily be renamed).

      With $filename = "IMG_3552.JPG" a call to mime_content_type() would return 'image/jpg' and renaming the file to "IMG_3552.txt" would still return the same result as the file is still an image and not text.
      Stephen
      Learn Modern JavaScript - http://javascriptexample.net/
      Helping others to solve their computer problem at http://www.felgall.com/

      Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

      Comment

      Working...
      X