PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] How to save each character of string in different column

 August 15, 2022     csv, input, output, php, string     No comments   

Issue

i am creating a new CSV file from the user input in php like this:

public function handle()
{
    $a = readline('Enter a string: ');
    $list = array (
        array($a)
    );
    
    $fp = fopen('file.csv', 'w');
    
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    
    fclose($fp);
    echo PHP_EOL . "CSV created!";
}

and getting the output like this:

enter image description here

but i want the output to be like this:

h,e,l,l,o, ,w,o,r,l,d

each character in different column

how can i archive this?


Solution

You can split a string into chunks—in this case, every chunk will be 1 character long—with str_split.

    $a = readline('Enter a string: ');
    $list = array (
        str_split($a)
    );

If later you want to add some more columns, then you can do:

    $a = readline('Enter a string: ');
    $list = array (
        array_merge(array("foo", "bar"), str_split($a))
    );

Edit:

In your question you ask for "every character in a different column", but from your comment I take it you want one column but the characters split by spaces? In that case:

    $a = readline('Enter a string: ');
    $list = array (
        implode(',', str_split($a))
    );

fputscsv will make sure that the string is escaped properly.

If you want both multiple columns and every column ending in a space, then split the string as normal but also modify every array entry by adding a space at the end:

    $a = readline('Enter a string: ');
    $list = array (
        array_map(
          function($char) { return "$char,"; },
          str_split($a)
       )
    );

array_map will run a function ("callable") for every array entry.



Answered By - RickN
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing