itssami 0 Report post Posted May 3, 2006 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)------------------ Share this post Link to post Share on other sites
WindAndWater 0 Report post Posted May 3, 2006 (edited) 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. Edited May 3, 2006 by WindAndWater (see edit history) Share this post Link to post Share on other sites
jlhaslip 4 Report post Posted May 4, 2006 <?php$data = array(); // declare an array$source = 'string here'; // string to break down into array elementsfor ($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. Share this post Link to post Share on other sites
Javache 0 Report post Posted May 17, 2006 What could be the use of this ? Share this post Link to post Share on other sites
Spectre 0 Report post Posted May 17, 2006 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: 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; }} Share this post Link to post Share on other sites