php - How can I check if a username already exists in a file and also add his points to him? -


i intentionally want use text file this. read text file , want check if username exists in text file or not , want either add username text file if doesn't exists or add points him.

my current code:

<?php $myfile = fopen("test.txt", "r") or die("unable open file!"); $file = fread($myfile,filesize("test.txt")); //echo $file; fclose($myfile);  //$username = $_request['username']; //$points = $_request['point']; $username = 'chinmay'; //chinmay username unique $points = 200; //if username chinmay not exitst insert first time otherwise if username chimay exist next onwards point update everytime in text file.  $myfilewrite = fopen("test.txt", "a") or die("unable open file!"); $txt = $username."|".$points."\n"; fwrite($myfilewrite, $txt);  fclose($myfilewrite); ?>  

test.txt:

chinmay|800 john|200 sanjib|480 debasish|541 

this complete code. requirement is:

  • \n not working when using text inserted in same line.
  • how can check duplicate username?
  • if found username how can update user points?

i googled last 2 hours not getting solution. have no idea problem.

this should work you:

first use file() read file array. can use array_map() loop through each line , explode() | delimiter. after can use array_column() username key points value. this:

array (     [chinmay] => 1200     [john] => 200     [sanjib] => 480     [debasish] => 541     [chinmayx] => 200 ) 

with array can check if username exists or not. if not add array , add points it.

after adding points username can change data in same format , save file_put_contents().

full code:

<?php      $lines = file("test.txt", file_ignore_new_lines | file_skip_empty_lines);     $usernames = array_column(array_map(function($v){         return explode("|", $v);     }, $lines), 1, 0);      $username = "chinmayx";     $points = 200;       if(!isset($usernames[$username]))         $usernames[$username] = 0;     $usernames[$username] += $points;      foreach($usernames $k => $v)         $data[] = "$k|$v" . php_eol;      file_put_contents("test.txt", $data);  ?> 

edit:

if have php under 5.5 replace:

$usernames = array_column(array_map(function($v){     return explode("|", $v); }, $lines), 1, 0); 

with this:

$lines = array_map(function($v){     return explode("|", $v); }, $lines);  $usernames = array_combine(     array_map(function($v){         return $v[0];     }, $lines),     array_map(function($v){         return $v[1];     }, $lines) ); 

also if want top 10 users, rsort() array , take array_slice() of first 10 elements, e.g.

rsort($usernames); $topusers = array_slice($usernames, 0, 10); print_r($topusers); 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -