Jump to content

strange problem in a function

- - - - -

  • Please log in to reply
1 reply to this topic

#1
MIMi King

MIMi King

    Newbie

  • Members
  • Pip
  • 5 posts
Hi everyone,
I'm writing a function that divides a string into an array, by a symbol. the whole function works, but when i want to print the array by print_r it returns null, but when i put the print_r into the function it works perfect... i think that it's a problem with the variable and array defining progress... and maybe it gets defined only into the function and when function finishes it gets undefined... here's the code.. any help appreciated :

<?php

function convtoarray($sym,$text,$array){

	$wordcount = 0;

	for ($i = 0; $i < strlen($text); $i++) {

		if($text[$i] != $sym) {

		$word=$word . $text[$i];	

		} elseif ($word != "") {

			$array[$wordcount] = $word;

			$wordcount++;

			$word = "";

		} 

		if ($i == strlen($text)-1) {

		$array[$wordcount] = $word;

			$wordcount++;

			$word = "";

		}

	}

	print_r($array);

	echo "</br>Detected ".$wordcount." Words!";

}

$str = "Hello World!";

convtoarray(" ",$str,$mysamplearray);

?>


i don't want to use the explode function... i'm just doing this to improve my programming skills!

thank you!

#2
MIMi King

MIMi King

    Newbie

  • Members
  • Pip
  • 5 posts
HI... i changed the code and now it works right :

function convtoarray($sym,$text){

	$wordcount = 0;

	for ($i = 0; $i < strlen($text); $i++) {

		if($text[$i] != $sym) {

		$word=$word . $text[$i];	

		} elseif ($word != "") {

			$array[$wordcount] = $word;

			$wordcount++;

			$word = "";

		} 

		if ($i == strlen($text)-1) {

		$array[$wordcount] = $word;

			$wordcount++;

			$word = "";

		}

	}

return $array;

}

$str = "Hello World!";

$array = convtoarray(" ",$str);

print_r($array);






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users