How to create a function in PHP

I am trying to create a function called saveorder . This is my code:

 <?php //function foo($arg_1, $arg_2, /* ..., */ $arg_n) function saveorder($orderid,$txnid,$date,$amount) { $a_str = array( "orderid"=>"175", "txnid"=>"RC456456456", "date"=>"54156456465", "amount"=>"109$" ); $file = 'order.dat'; $contents = implode("|", $a_str); $contents .= PHP_EOL . PHP_EOL; file_put_contents($file, $contents); } echo "function will return=".saveorder($orderid); ?> 

I think I am doing it wrong because I never created my own function. However, I want to create this function to keep order in the order.dat file. Can someone help me create this feature? I try very hard, but I canโ€™t create it.

+4
source share
2 answers

you didnโ€™t have a return, otherwise the function is fine :)

 function saveorder($orderid,$txnid,$date,$amount){ $a_str = array( "orderid"=>$orderid, "txnid"=>$txnid, "date"=>$date, "amount"=>$amount ); $file = 'order.dat'; $contents = implode("|", $a_str); $contents .= PHP_EOL; file_put_contents($file, $contents, FILE_APPEND); return $contents; } echo "function will return=".saveorder("175","RC456456456","54156456465","109$"); 

EDIT: added FILE_APPEND

+7
source

In fact, you did not return any value to your function, so it really worked correctly.

You need to add, for example, the next element at the end of the function

 <?php function saveorder($orderid,$txnid,$date,$amount) //function foo($arg_1, $arg_2, /* ..., */ $arg_n) { $a_str = array( "orderid"=>"175", "txnid"=>"RC456456456", "date"=>"54156456465", "amount"=>"109$" ); $file = 'order.dat'; $contents = implode("|", $a_str); $contents .= PHP_EOL . PHP_EOL; res = file_put_contents($file, $contents); if(res){ return true; } else { return false; } } echo "function will return=".saveorder($orderid); ?> 
0
source

All Articles