Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save variable using fwrite

Tags:

php

fwrite

I just trying to understand how to use fwrite. In the below code, i am trying to save the output in the text file. I am just getting an empty txt file. Can anyone please tell me what i am doing wrong here

<?php
    $name =  fix_name("ALAN", "james", "LiM");
    echo $name[0] . " " . $name[1] . " " . $name[2];
    function fix_name($n1, $n2, $n3) {
        $n1 = ucfirst(strtolower($n1));
        $n2 = ucfirst(strtolower($n2));
        $n3 = ucfirst(strtolower($n3));

        return array($n1, $n2, $n3);

}
    $fp = fopen("name.txt", "wb");
    $written = fwrite($fp, $name);
    fclose($fp);

?> 
like image 973
Faisal Mukhtar Avatar asked May 09 '26 04:05

Faisal Mukhtar


1 Answers

You are passing an array to fwrite.
If you enable error reporting with

error_reporting(E_ALL);

You would get a warning saying

Warning: fwrite() expects parameter 2 to be string, array given in file.php on line 16

Either return a string from your function

return $n1 . ', ' . $n2 . ', ' . $n3;

Or outside the function, use implode to get a string from the elements of the array

$name = implode(', ',fix_name("ALAN", "james", "LiM"));

Also, outside the function, print out just the $name variable

print $name;

In your text file you will have this

Alan, James, Lim
like image 103
Alex Andrei Avatar answered May 11 '26 20:05

Alex Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!