Ramaraju.d
Ramaraju.d

Reputation: 1353

How to remove new line or line breaks while parsing data from an array

I am trying to parse a csv file to insert the csv contents into my Database. After the data is parsed the array looks like

Array
(
    [AirportCode
] => GKA

)

and i would like to extract the AirportCode GKA and insert it. Everything looks fine but the key and Value in the above array having line breaks.

Sample code:

foreach($data['csvData'] as $field)
{
    print_r($field);
    $AirportCode =  str_replace(PHP_EOL, '', $field['AirportCode']);

    echo $AirportCode ;     
}

But the AirportCode is always returning empty. I just want to get-rid of those line breaks. Can someone help me...?

Upvotes: 0

Views: 1437

Answers (2)

Steve
Steve

Reputation: 20469

there is no array key called 'AirportCode' the actual key has a line break in it. I would create a clean array by looping through the key value pairs, and adding them to a new array:

$clean=array();
foreach($data['csvData'] as $key => $value){
    $ckey = str_replace(array("\r", "\n"), '', $key);
    $cvalue = str_replace(array("\r", "\n"), '', $value);
    $clean[$ckey]=$cvalue;
}

var_dump($clean);

Upvotes: 1

Zander Rootman
Zander Rootman

Reputation: 2208

Untested
I'm not sure about str_replace() capabilities on recognizing newline characters by using the escape reference, but it's worth a shot.

However your airport code is returning nothing, because the actual key seems to have a \n (new line character) in.

function fixArrayKey(&$arr)
{
    $arr=array_combine(array_map(function($str){
        return str_replace("\n ","",$str);
    },array_keys($arr)),array_values($arr));

    foreach($arr as $key=>$val)
    {
        if(is_array($val)) fixArrayKey($arr[$key]);
    }
}

For your array values however you could just use:

function fixArrayValue($arr)
{
    $return = array();
    foreach($arr AS $key => $value){
        $return[$key] = rtrim($value, "\n");
    }
    return $return
}

Upvotes: 2

Related Questions