1

How can I assign values to an array of strings using an index? Let's say I don't know what the values of the strings are in the array, so I use keys instead.

Array that could be any list of strings:

$this->cols = array(
    'name',
    'age'
);

assignment function

$row = 1;
        if (($f = fopen($this->file['tmp_name'], "r")) !== FALSE) {
          while (($data = fgetcsv($f, 0, ",")) !== FALSE) {
                $num = count($data);
                $row++;
                for ($c=0; $c < $num; $c++) {
                    $colName = $this->cols[$c];
                    $this->cols[$colName] = $data[$c];
                }
            }

How can I assign the value ($data[$c]) to the corresponding index if I don't supply its value, but rather use a numerical index? I know for a fact that I can access the array like this because

$colName[0] = 'name'
$colName[1] = 'age'

But when I run the function I get

0 => nameValue
1 => ageValue

Instead of

'name' => nameValue
'age' => ageValue
3
  • What is $f? Where does it come from? Commented Jan 10, 2015 at 18:36
  • I suggest you start looking into the php documentation. There you will find a wealth of array handling functions. All explained in details including examples. Commented Jan 10, 2015 at 18:37
  • The main problem I see is too many things happening at the same time. Try to separate the part where you read the file from the loop of it, then the assignment of the variables from the loop. In this way every bug/problem will be much easier to spot. Commented Jan 10, 2015 at 19:09

1 Answer 1

1

You're overwriting your own data:

 $num = count($data);
 $row++;
 for ($c=0; $c < $num; $c++) {
     // every row of the CSV will update the same keys
     $colName = $this->cols[$c];
     $this->cols[$colName] = $data[$c];

 }

 // I suggest adding a `break` after that for look to see the problem.
 break;

Alternatively, you could update the code to track all values:

 $num = count($data);
 $row_val = array();
 $this->cols[] = $row_val;
 $row++;
 for ($c=0; $c < $num; $c++) {
     // every row of the CSV will update the same keys
     $colName = $this->col_names[$c];
     $row_val[$colName] = $data[$c];

 }
Sign up to request clarification or add additional context in comments.

3 Comments

You're probably right but I haven't gotten that far yet. I just wanted to understand how to assign a value to an array based on indexes.
OK so the answer is make a new array to assign the values. Thanks.
actually the OP was not overriding..he was appending to the array. when i ran this code i got 4 elements with 0,1,name, age keys.

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.