Home » Php » Manipulate array in PHP

Manipulate array in PHP

Posted by: admin October 26, 2017 Leave a comment


I have compared two csv file and combine unique data to this array below:

array(5) { 
    [0]=> string(26) "john,[email protected],blah " 
    [1]=> string(29) "mary,[email protected],something " 
    [2]=> string(29) "jane,[email protected],blarg " 
    [3]=> string(25) "bob,[email protected],asdfsfd " 
    [7]=> string(22) "bob,[email protected],1232 " 

Now from this array, I would like to update array 3 to use 1232 instead of asdfsfd and delete array 7.

Any suggestion how can I achieve that in php?


The direct way can be:

$arr = $your_array;
$arr[3] = "bob,[email protected],1232 ";

Anyway, if you need to validate every time you recive an array you have to find some patters and use a foreach($arr as $ar){//do your staff} function.

    //he is your array:
$arr = array(
    '0'=>'john,[email protected],blah',
    '1'=>'mary,[email protected],somethin'
    //and ....
$new_array = array();
foreach($arr as $key=>$val)
    $item = explode(',',$val);//explode string by , and get an array
    //$item will be: array('john','[email protected]','blah');
    // $item[0] = user_name
    // $item[1] = email
    // $item[2] = the blah thing
    // validate your data or replace it
    // save data to new array
    $new_array[$key][0] = new user name or whatever
    $new_array[$key][1] = new email
    $new_array[$key][2] = new blah