-3

This has confused me, i am tiring to store an array as a variable before posting the variable into my database.

here is my code

foreach( $_POST['parts'] as $key => $value){
        $aparts .= $value.',';

    }

it stores $aparts fine but i get the Undefined variable error in the following line.

$aparts .= $value.',';

I am quite new and learning as i go I would like to know why this has happened :)

  • 5
    Define it before: `$aparts = '';`. – Blackhole Nov 05 '15 at 13:21
  • 2
    "*I know the easiest method would to turn off error reporting*", no - the easiest method would be to fix it, by simply defining it as already suggested. – Qirel Nov 05 '15 at 13:26
  • @Qirel I agree with the answers from my question i have fixed the problem and learnt something so i am very grateful i have deleted that comment from my original question – Richard Ransom Nov 05 '15 at 13:29
  • 2
    Suppressing errors and ignoring errors (even if they are just notices) are bad practice, one should always write code in a way that it always handle them. Good thing you managed to figure it out! (Even thought this is a duplicate question, you would've found the answer [on this StackOverflow](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index)). :) – Qirel Nov 05 '15 at 13:32

3 Answers3

7

It´s because you´re trying to append to $aparts without it being defined. To fix it define it before the foreach:

$aparts = "";
foreach( $_POST['parts'] as $key => $value){
   $aparts .= $value.',';
}

PHP has also a function called implode() which has the exact same result as your foreach loop:

$aparts = implode(",", $_POST['parts']);
Daan
  • 12,099
  • 6
  • 34
  • 51
  • Thanks :) i have used your addition answer it is a tidier way to do this thanks for your answer – Richard Ransom Nov 05 '15 at 13:25
  • And an explode() function that will get you your array from the string once you read it. http://php.net/manual/en/function.explode.php - But this will cause issues if any of your 'parts' have commas. – Mikel Bitson Nov 05 '15 at 13:26
3

You could use serialize() when inserting and unserialize() when reading from the database. This will take an array and create a string for you that you can save. Then, unserialize takes that string and creates the array again.

This will work even if your content has commas in it. Your current method (and the other answer) will not, it will separate a single string with a comma into two separate entries in your final array.

Mikel Bitson
  • 3,583
  • 1
  • 18
  • 23
1

You should declare $apartsbefore the foreach statement:

$aparts = '';
foreach ($_POST['parts'] as $key => $value) { //...
godzillante
  • 1,174
  • 1
  • 17
  • 32