0

I want to create dynamic associative array from two array's one array is be used ($l_arr) for key and other array is used for value ($r_arr) when i display $map in output i can see there is associative array created but when i print echo $map['key'] output is blank please help me guyz. here is the code and output,

<?php


$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);

for($i=0;$i<$n;$i++)
{
     $arr_temp = fgets($handle);
     $l_arr[$i]= preg_replace("/[0-9,.]/", "", $arr_temp);
     $r_arr[$i]=preg_replace("/[^0-9,.]/", "", $arr_temp);

}
for($i=0;$i<$n;$i++)
{
$arr_temp = fgets($handle);
$op[$i]=$arr_temp;
}
          for($i=0;$i<$n;$i++)
    {

        $map[$l_arr[$i]]=$r_arr[$i];

     }
print_r($map);

echo "value of sam is".$map['sam'];

?>

and output is

Array
(
    [sam 
] => 99912222
    [tom 
] => 11122222
    [harry 
] => 12299933
)

value of sam is

1 Answer 1

1

As you can probably see, there are whitespaces in your output - look at new lines after each array index. You need to trim() your preg_replace() here:

$l_arr[$i] = trim(preg_replace("/[0-9,.]/", "", $arr_temp));
$r_arr[$i] = trim(preg_replace("/[^0-9,.]/", "", $arr_temp));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.