common Posted March 10, 2009 Share Posted March 10, 2009 Hey I have a string and need to break it up so that the words are the values in a array. Then i want to create a list of the words, but i want to give the array key next to each word. For example if i have "Hallo my name is Jan". I want the words in a list and numbers form 0 to 5 next to each word. How do i get the numbers because i've got the words in a list. Quote Link to comment https://forums.phpfreaks.com/topic/148808-arrays/ Share on other sites More sharing options...
rhodesa Posted March 10, 2009 Share Posted March 10, 2009 <?php $string = "Hallo my name is Jan"; $list = preg_split('/\s+/',$string); $array = array_combine($list,range(0,count($list)-1)); print_r($array); ?> Quote Link to comment https://forums.phpfreaks.com/topic/148808-arrays/#findComment-781426 Share on other sites More sharing options...
wildteen88 Posted March 10, 2009 Share Posted March 10, 2009 EDIT: Beaten to it $string = 'Hallo my name is Jan'; $words = explode(' ', $string); foreach($words as $key => $value) { echo "$key => $value<br />"; } Quote Link to comment https://forums.phpfreaks.com/topic/148808-arrays/#findComment-781428 Share on other sites More sharing options...
Mark Baker Posted March 10, 2009 Share Posted March 10, 2009 Or even use the single function that does exactly this $sentence = 'Hallo my name is Jan'; $wordsArray = str_word_count($sentence,1); print_r($wordsArray); Quote Link to comment https://forums.phpfreaks.com/topic/148808-arrays/#findComment-781434 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.