1

I have a text file with contents such as following which are ids and names.

23414,apple
24323,orange
64563,banana

In a PHP file I read in the content of the text file into an array like

$itemArray = array();

$records = file('/path/to.file/guilds.txt');
foreach ($records as $line) {
$lineArray = explode(',',$line);
array_push($itemArray,$lineArray);  
}

If I know the id of a particular record say 24323, how can I return the associated name, orange. All ids are unique. I tried something like the following with no luck.

$id = 24323;

echo "Result:" . array_search($id, array_column($itemArray,1,0));

Edit: To clarify code.

1
  • you can achieve the goal with 2 lines of code Commented Sep 6, 2017 at 6:58

3 Answers 3

2

If I know the id of a particular record say 2, how can I return the associated name, orange. All ids are unique. I tried something like the following with no luck.

Since you said ids are unique, better you create array like below,

$itemArray = array();

$records = file('/path/to.file/guilds.txt');
foreach ($records as $line) 
{
    $lineArray = explode(',',$line);
    $itemArray[ $lineArray[0] ] = $lineArray;  

   /* Use below if you just want to store name 
      $itemArray[ $lineArray[0] ] = $lineArray[0];  
   */
}

and you can access them easily like below

$id = 24323;
print_r( $itemArray[$id] );

/*You will get below
          Array
          (
            [0] => 24323
            [1] => orange
           )

*/

// and if you want just to print orange then
echo $itemArray[$id][1];   // orange
Sign up to request clarification or add additional context in comments.

4 Comments

Why not $itemArray[ $lineArray[0] ] = $lineArray[1];?
@Aydin: see op has edited look at his ids, and OP hasn't made clear so I stored entire array instead of just one element
Why not store $itemArray as (23414=>'apple', 24323=>'orange', ...) ? And retrieve it with $itemArray[24323];(will produce 'orange').
@Aydin: please see my edit, you can store, I had put it in comment let OP select whichever he/she want
0

I think the problem is this, when the text file was read, exploded and pushed into array, each was treated as an individual element of the array which results in array structure like:

$itemArray[0] => 1
$itemArray[1] => Apple
$itemArray[2] => 2
$itemArray[3] => Orange
$itemArray[4] => 3
$itemArray[5] => banana

So I think you should read with index

Comments

0

Short preg_match_all + array_combine functions solution:

preg_match_all('/^(?P<id>[0-9]+),(?P<name>\w+)\s*/m', file_get_contents('/path/to.file/guilds.txt'), $m);
$result = array_combine($m['id'], $m['name']);

print_r($result[24323]);

The output:

orange

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.