Search code examples
phpfunctionreturn

Php how to correctly use return function?


Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result

$fullname = "Ayoub Chafik" ;

function orderID($data){
    $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    $str[0];

}
// I want to see resulte here of this function
   echo orderID($fullname) ;


?>

This is the second Block

<?php

$fullname = "Ayoub Chafik" ;

function orderID($data){
    echo $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    echo $str[0];

}

echo orderID($fullname) ;


?>

Solution

  • As I explained in comment you store it in a variable and return it. Check below example. Also it is a good practice to open the {} even its only one line for more readability.

    $fullname = "Ayoub Chafik" ;
    
    function orderID($data) {
        $string  = strtoupper($data);
        $strs    = explode(" ", $string);
        $results = '';
    
        foreach($strs as $str) {
            $results .= $str[0];
        }
    
        return $results;
    }
    
    echo orderID($fullname) ;