SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Apr 2004
    Location
    Boston
    Posts
    482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    creating seperate variable from string

    Hello,

    I have a string of data and I need to separate it into individual values.

    For example:

    PHP Code:
    $result "Randy; Mike; John; Cathy"
    I need to separate them so each is an individual value in an array.

    PHP Code:
    $result[0] = "Randy";
    $result[1] = "Mike";
    $result[2] = "John";
    $result[3] = "Cathy"
    Can i do this with list()?

    Thanks

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Sure, explode() will do this for you.
    PHP Code:
    <?php
    $names 
    explode(
        
    '; ',
        
    'James; Anthony; John; Robin; Joe'
    );

    print_r(
        
    $names    
    );

    /*
        Array
        (
            [0] => James
            [1] => Anthony
            [2] => John
            [3] => Robin
            [4] => Joe
        )
    */
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Evangelist AlienDev's Avatar
    Join Date
    Feb 2007
    Location
    UK
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Instead of exploding on "; " (with the space), you might want to explode on only the ";" and the get rid of any whitespace separately.
    $names = array_map('trim', $alreadyExplodedArray);

    Advantage is that it works no matter much many spaces or whitespace is before/after the ";".
    Me on StackOverflow | Blog & personal website.

    I mostly use: PHP, Java, JavaScript, Android.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •