any good php programmer to explain this?

  • Thread starter Thread starter the town man
  • Start date Start date
T

the town man

Guest
hi there.....

i want to remove 'undefined' from $arr...i have three functions and only the last one returns the wanted result...can you explain why the first and second functions can't return the wanted result.....


$arr=array(1,2,4,'undefined',1,
'undefined');

$remove_undefined=array();

$remove_undefined=
remove_undefined($arr);

1 :

function remove_undefined($arr)
{
if(in_array('undefined',$arr)) {

$loc=array_search('undefined',$arr);

unset($arr[$loc]);

remove_undefined($arr);
}

return $arr;
}

print_r($remove_undefined); //Array ( [0] => 1 [1] => 2 [2] => 4 [4] => 1 [5] => undefined )

..........................

2 :

function remove_undefined($arr)
{
for($i=0;$i<count($arr);$i++) {

if($arr[$i] == 'undefined')

unset($arr[$i]);
}

return $arr;
}

print_r($remove_undefined); //Array ( [0] => 1 [1] => 2 [2] => 4 [4] => 1 [5] => undefined )

.........................

3 :

function remove_undefined($arr)
{
$i=0;

foreach($arr as $v) {

if($v == 'undefined')

unset($arr[$i]);

$i=$i+1;
}

return $arr;
}

print_r($remove_undefined); //Array ( [0] => 1 [1] => 2 [2] => 4 [4] => 1 )

.........................

thanks...
 
Back
Top