Spliting An Array

free web hosting
Open Discussion > CONTRIBUTE > Computers > Programming Languages > PHP Programming

Spliting An Array

itssami
I got this excercise from school, im trying to understand it but im unable..can someone help me ?its very small problem but im not getting the point.

------------------
Create a string: $wholestring = “splitwholestring”;
And split it to array using for loop. So that you have a array containing all the letters of the string: array[0] == s, array[1] == p, etc. Display results. (hint: strlen(), substr() - functions are useful)
------------------

Reply

WindAndWater
Well lets look at the functions you have:
strlen($string) returns the number of characters in the string.
substr($string, $start, $length) returns the string of length $length, starting at the $start character.
In order to add things to an array, you must first initialize it: $arr = array(); and then you can automatically add new elements by using $arr[] = $nextElement;

So a psudo-code way to do your assignment would be:
1) Get the length of the entire string.
2) For each character in the string, starting at the first, get that single character, and add it to the array.

Hopefully that helps you get started. If you want to be smart with your teacher, you can point out that php strings already work like arrays.

p.s. I know code is generally put into code tags, but I decided to leave them out as I'm using the code in mid sentence.

Reply

jlhaslip
CODE

<?php
$data = array(); // declare an array
$source = 'string here'; // string to break down into array elements
for ($i=0; ($i<=strlen($source)-1); $i++) {
     $data[] = $source{$i};
     echo $i . ' - ' . $source{$i} . '<br />'; // echo array elements and their key value
     }
var_dump($data); // dump the array to the browser to confirm values
?>

Like this?
The echo and the var_dump are in the script only to confirm that the string is converted into an array. Delete as required.

Reply

Javache
What could be the use of this ?

Reply

Spectre
There is a function in PHP5 str_split() which allows you to split a string into an array. In earlier versions, jlhaslip's suggestion would work fine, but here is a possibly more useful method which emulates the str_split() function:

CODE
if( !function_exists('str_split') ) {
   function str_split( $string, $split_length = 1 ) {
      if( $split_length < 1 || !is_numeric($split_length) ) {
            trigger_error('str_split(): The length of each segment must be greater than zero',E_USER_WARNING);
            return false;
      }
      $split_array = array();
      for( $i=0;$i<strlen($string); ) {
         $split_string = substr($string,$i,$split_length);
         $i += strlen($split_string);
         $split_array[] = $split_string;
      }
      return $split_array;
   }
}

 

 

 


Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. php "the length of each segment must be greater than zero" - 391.27 hr back. (1)
  2. php strings "from array" - 447.48 hr back. (1)
  3. storing str_split to an array - 1000.86 hr back. (1)
Similar Topics

Keywords : spliting, array

  1. Array Pointers Can Be Backwards
    (Kind of) (7)
  2. [ruby]lite Multi-dimensional Array
    (0)
    Hey everyone, What I have here is a really simple Multi-Dimensional Array class. This is a Lite
    version with only very basic features. It supports 2- and 3-Dimenional Arrays, and it only really
    has capabilities for storing and accessing data. I am working on a fully featured version of the
    class, but it's going in a game engine I am working on that I'll hopefully be selling
    licenses for, so it would do no good to release all the classes in it. /biggrin.gif"
    style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> This class has relatively
    good p....
  3. Remove A Value From A Php Array Based On Its Value
    (5)
    I have an index array CODE $array[0] = 10; $array[1] = 12; ...
    Its kinda late and I'm falling asleep now but I had a quick look through PHP.net, and could not
    find what I'm after, Maybe I'm too sleepy, sorry, but if anyone knows off the top of their
    head a way to removed members in that array based on its value, i.e. I wanna remove values 12. I
    don't really want to do a loop but if I cant find any existing function to do it, then I may
    have to. Thanks for any help.....
  4. Getting An Array Value Of A Dynamic Variable
    (9)
    Ok i can't believe I need help in php but I can't figure this out... If i have an array,
    lets say called test, how do i get a certain value from that array when referencing it dynamically
    by either a string or another variable? Example: CODE $test=array(1,2,5);
    $name="test"; //Doesn't work: echo $$name[0]; /Doesn't
    work: echo ${$name}[0]; ....
  5. Using Multiple Selection Array In Table To Order Data
    Using multiple selection array in table to order data (1)
    have a form that has a multiple select choice, like this: CODE <form method="post"
    action="display.php" <select multiple name="selectsort[]">
    <option value="code">Code</option> <option
    value="amount">Amount</option> <option value="dateammended">Date
    Ammended</option> <option value="expreviewdate">Expiration/Review
    Date</option> <option value="effectivedate">Effective Date</option>
    <option value="e....
  6. What Is A Fibonachi's Array?
    Deffinition about Fibonachi's array (5)
    Fibonachi's array is a mathematical array noticed in a lot of chemistry, science and biology
    advents. It is an array of numbers which addend of two before numbers give next article of array,
    but this rule doesn't apply for first and secon article 1 and 1. Appearance of array: 1, 1, 2,
    3, 5, 8, 13, 21, 34, 55, 89, 144... Array got name per Italian mathematician Fibonachi.....
  7. Reading Files From Directory To Array, And Using $_get To Get Them
    Simple way to manage lot's of files (2)
    Some user posted a similar problem i had when i tried to figure out how to update content on my
    website in less work as possible. This is just part of the "big" plan i have for my site but it can
    be helpfull to you guys if you like FlatFile. I hope that mod's don't mind me posting the
    same code here and on their forums, couse if they do i'll delete it from their forums
    /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif" /> So
    here's the situation. Let's say you have a folder called 'myfilesdirectory' on your
    s....
  8. [php] Walking Through Multidimensional Arrays
    Walk through multidimensional array with foreach and list (2)
    If you like PHP arrays like i do you probably wondered how to walk through multidimensional arrays.
    You can construct them maybe from your database or flat file, and output them with simple two
    functions foreach, and list.. Let's say we have something like this CODE $information
    = array (                         'id0001' => array ('ivan',
    'ivanovich', 'm', '24'),                         'id0002' =>
    array ('marko', 'markovich', 'm', '21'),             ....
  9. More Dynamic ?id=browsing With Php (associative Array)
    Just create array and watch php code do the rest (1)
    The thing that has been bugging me for a while was that switch statement that we use to create ID
    browsing (some use If-Ifelse but results are the same for both). I wanted to figure out a way to use
    more dynamic switch statement so that i only need to update my links array in order to create links
    for template. With use of foreach, array_keys, and in_array functions finally i managed to do so.
    Also i'm planing on changing foreach with array_walk but i'll do that later. Now for the
    code.. First we create an associative array something like this CODE $gl....
  10. Array Problem
    (4)
    I'm having trouble with an assignment for my data structures class.


    I have to simulate a
    card player getting a a pile of 52 cards (a full deck).
    ....
  11. How Do I Create An Array Of Objects?
    The code in the tutorial I have read returns an error upon compilation (3)
    I want to create an array of type Cards. Is this the right way of doing it? CODE Card
    decker[]; decker = new Card[5]; I always get the error DeckofCards: java:47:
    missing return statement whenever I compile this.....
  12. What Is Maid?
    (Massive Array of Idle Disks) (2)
    MAID stands for Massive Array of Idle Disks. This is a technology that promises to provide massive
    scalable storage at a very low cost. MAID will be used where there is a need to archive large
    amount of data scaling up in terabytes. It also provides quick access to large amount of data. At
    present only one company named Copan Systems offers the solution as this concept is relatively new.
    Actually in older times and even now there is huge amount of data soted and accesed from tape
    drives. The main drawback of Tape drives is their very slow access speeds. Also, when hug....
  13. Converting Characters In A Variable To Individual Values In An Array
    turning variables into arrays (2)
    Say I have a variable such as $nav_item and it had to contents Home . IE: CODE
    $nav_item = 'Home'; How would I make so that $nav_item was an array and
    had the following contents? CODE $nav_item = array ('h', 'o',
    'm', 'e'); With the case changing (ie H would become h and U
    would become u ) EDIT: Okay found out that I could change the case with
    array_change_key_case ($nav_item, CASE_LOWER); ....
  14. Hard Drive Array
    help (5)
    Hi guys, well im building my dreamed pc, i need a lot of resources cause i want to get full into the
    3d. And one of the things i need is to build and array of hardrives, but i have a bunch of questions
    about it 1- How do you do that ? lol 2- How many hard drives can i put in the array? is it
    determined by the motherboard? 3- How fast do you recommend the hard drives must be? 4- THeres a
    relation between the number of hard drives and the amount of ram i need? 5- In order to run well
    what else do i need? Apreciate your help.....
  15. Opengl Pointer To Array
    Value Pointed..? (1)
    I'm playing around wtih openGL and trying to get the hang of c/c++(very frustrating at times). I
    pass a pointer to an array from an object to my main via a get method. If I print out(cout) the
    pointer(p) and the value pointed to (*p) from main, *p prints the decimal equivilent of the memory
    address p, not the value that p should be pointing to. Within the object, everything is peachy, its
    just when I pass the pointer to to main that this happens. The arrays plist and vlist in
    meshloader are the ones im having trouble with. Any ideas? Thanks in advance. Feel free t....
  16. What Is Raid?
    or Redundant Array of Independent Disks (11)
    Using RAID can improve performance or security of data and data transfer on any computer (that has
    drives that support). RAID is a system for sharing or duplicating data among various harddisks.
    Depending on which level one sets RAID up a person can get increased data integrity,
    fault-tolerence, and/or capactity than single disk drives. RAID also makes the computer see multiple
    drives as one logical drive. RAID is typically used on servers, either to provide more efficiency or
    to backup all data. The most common levels of RAID are 0 and 1. RAID 0: This level is usuall....
  17. Remove Objects From Array With Unset
    (2)
    Have been trying to solve this for a long time now, so I thought I´d give you guys a chance to break
    it! I want to remove an object from an array that I store in a Session object. I´ve written a
    function that takes an array and an id as parameters. Checks if one of the objects has the id I want
    to remove and then it´s supposed to remove it. Quite simple, that´s why I cant see why it doesnt
    work! Here´s the code: CODE function Remove_prod($id2,$AL) {
    print_r($AL); foreach ($AL as $prod) if($prod-....
  18. Array Size Limitations
    (2)
    I'm writing a win32 console app and am about to implement an array of size 10,000,000 . Can
    someone tell me what this would do ? Would my memory be able to handle it or would it cause other
    variables to lose their value ? I may just end up writing the array to a text file and then just
    searching it when I need it but I would rather not if I didn't need to. Can someone tell me what
    the limit is ? kvarnerexpress....
  19. parse mysql table into array
    (5)
    i made a mysql db class and now i want to make a function that parses the table into an array, i
    dont have that much php experience so can anyone help me? CODE <?php
    if(!class_exists('cDB')) {  class cDB  {   var $lDB;
      function cDB($name)   {    $this->lDB = mysql_connect();  
     mysql_select_db($name, $this->lDB);   }     function table($name)
      {    //parse table array here   }     function __destruct()   {
       mysql_clo....
  20. Using A Timer In A Array...
    (2)
    I'm usually very well a creating a problems and then finding a solution. However this time
    I'm stumped. I'm attempting to create timers.. I know this is possible by doing...
    visual basic code:--------------------------------------------------------------------------------
    Option Explict Dim WithEvents tmrTimer1 As VB.Timer Private Sub Form1_OnLoad() Set tmrTimer1 =
    Me.Controls.Add("VB.Timer", "Timer1") End Sub
    -------------------------------------------------------------------------------- Now, what I need
    is to be able to create those timers, but creat....

    1. Looking for spliting, array

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for spliting, array

*MORE FROM TRAP17.COM*
advertisement



Spliting An Array



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE