Jump to content


Photo

is_array PHP Solutions HELPPPPP!

array coding

Best Answer .josh, 30 July 2013 - 01:48 PM

A form can have any number and type of elements(text fields, radio buttons, checkboxes, hidden fields, dropdowns, etc.).

$_POST is an array of all the form elements and their values that was submitted. Depending on how complex the form is, $_POST can be anything from an array with a single element, to a multi-dimensional array.

For example, with a simple form like this:
 

<?php
echo "<pre>";print_r($_POST);echo "</pre>";
?>
<form action='' method='post'>
  <input type='text' name='email' />
  <input type='submit' name='submit' value='submit' />
</form> 
$_POST will look like this:
Array
(
    [email] => foo@bar.com
    [submit] => submit
)
But with a more complex form, like one with checkboxes:
 
<?php
echo "<pre>";print_r($_POST);echo "</pre>";
?>
<form action='' method='post'>
  <input type='text' name='email' /> <br/>
  <input type="checkbox" name="animals[]" value="dog" />dog <br/>  
  <input type="checkbox" name="animals[]" value="cat" />cat <br/>  
  <input type="checkbox" name="animals[]" value="mouse" />mouse <br/>  
  <input type='submit' name='submit' value='submit' />
</form>
$_POST will look like this:
Array
(
    [email] => foo@bar.com
    [animals] => Array
        (
            [0] => dog
            [1] => mouse
        )

    [submit] => submit
)
So from this, is_array($_POST['email']) would be false, since that is just a string "foo@bar.com". But is_array($_POST['animals']) would be true.

Checking whether or not the posted value is an array may or may not be relevant to the actual code example in the book; you'd have to post the form code from the book for us to determine that. Go to the full post


  • Please log in to reply
12 replies to this topic

#1 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 28 July 2013 - 01:42 PM

I've been trying to learn PHP with the PHP Solutions book second editions by David Powers. I seemingly can't find anyway of contacting him about the code I found in the book.

 

 

<?php
foreach ($_POST as $key => $value) {

// assign to temporary variable and strip whitespace if not an array

$temp = is_array($value) ? $value : trim($value);
// if empty and required, add to $missing array
if (empty($temp) && in_array($key, $required)) {

$missing[] = $key;
} elseif (in_array($key, $expected)) {

// otherwise, assign to a variable of the same name as $key

${$key} = $temp; }

 

 

I understand that is_array checks whether or not $value is an array but I can't find a scenario in which it would be array and therefore why it would be there at all.

 

Also I the last part relies on the fact above which I don't understand as well. 



#2 mac_gyver

mac_gyver

    Advanced Member

  • Administrators
  • 2,244 posts

Posted 28 July 2013 - 01:47 PM

a form field can be an array name, name='some_name[]'. this allows you to have multiple related fields, typically checkboxed/radiobuttons, that share a common name and can be iterated over as an array after they have been submitted.


multi-purpose programming fool and resident naysayer [We try not be negative in replies, but telling someone what they're doing wrong, while staying politically correct, isn't always going to happen.]

#3 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 28 July 2013 - 01:53 PM

Wait so $value is a form field? I really don't understand this portion of his code. I thought $value was user input. And I was thinking why user input would ever be an array? I thought $key would be the form fields. I'm sorry I'm a beginner and this made me quit confused.



#4 AbraCadaver

AbraCadaver

    Cracka Memba

  • Gurus
  • 1,888 posts
  • LocationThe Republic of Texas

Posted 29 July 2013 - 09:57 AM

Form fields are user input.  If you submit the following checkboxes named: cb[0], cb[1], cb[2] with each one having a value of 'yes', and all are checked, then when submitted you have a $_POST['cb'] array.  So the $key is 'cb' and the $value is an array with three items.  The print_r() of the $_POST array would look like:

Array
(
    [cb] => Array
        (
            [0] => yes
            [1] => yes
            [2] => yes
        )

)

Edited by AbraCadaver, 29 July 2013 - 09:57 AM.

mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

#5 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 29 July 2013 - 04:52 PM

Thank you Cadaver. My only question now is how this would apply to a form in which users type in say their e-mail address or leaving comments?



#6 jcbones

jcbones

    Advanced Member

  • Gurus
  • 2,439 posts
  • LocationNorth Carolina

Posted 29 July 2013 - 05:19 PM

<?php
foreach ($_POST as $key => $value) { //for each of the user inputs (form fields).
// assign to temporary variable and strip whitespace if not an array
$temp = is_array($value) ? $value : trim($value); //if the value is an array, assign it to $temp, otherwise trim all the whitespace from the value, then assign it to $temp.
// if empty and required, add to $missing array
if (empty($temp) && in_array($key, $required)) { //if $temp is empty AND the current $key is not in the $required array.
$missing[] = $key; //assign the current $key to an array named $missing.
} elseif (in_array($key, $expected)) { //If non of the above are true, but the current $key is in the $expected array.
// otherwise, assign to a variable of the same name as $key
${$key} = $temp; } //assign the $temp variable to a variable of the same name as the current $key (variable variable), which is the same name as your form field name.
}
//any data passed that isn't in the $required array, nor in the $expected array WILL BE discarded.

 

I tried some clarification.



#7 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 29 July 2013 - 10:01 PM

The context is that value would be user input in a form. I'm confused about the is_array portion in the 4th line. The user input shown  in the book states would be something like an e-mail, name, or comment. I'm confused as to why is_array would be used. I mean when will user input every be an array? Wouldn't that make the condition always true? Anyways, thanks for the reply, I finally understood that last portion at the bottom, which I thought was assigning $key to the $temp variable defined above. 



#8 KevinM1

KevinM1

    Snarkimus Prime

  • Moderators
  • 5,189 posts
  • LocationNew Hampshire, USA

Posted 29 July 2013 - 11:31 PM

A collection of submitted checkboxes could be an array.

#9 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 30 July 2013 - 12:18 AM

I'm sorry if I didn't make it clear and that's also what I thought initially, it's in the PHP Solution 2nd Editions ( I know quite few people who have it), but the book states clearly that it's user text input.



#10 mac_gyver

mac_gyver

    Advanced Member

  • Administrators
  • 2,244 posts

Posted 30 July 2013 - 06:26 AM

that line of code is using a Ternary Operator - a short form of an if(){}else{} statement, in case (conditionally) the form field is an array. the code is not saying the form field must be an array, but if it is an array, the array is assigned to $temp. if it is not an array, the trimmed value is assigned to $temp. that line is the same as -

if(is_array($value)){
    // $value is an array, assign it directly $temp (since trying to use trim() on it won't do anything). the code should actually be part of a recursive function so that if the data is an array at this point, the function is called again to process the next level of the array
    $temp = $value;
} else {
    // $value is not an array, it is a scaler variable, assign the trimmed $value to $temp
    $temp = trim($value);
}

multi-purpose programming fool and resident naysayer [We try not be negative in replies, but telling someone what they're doing wrong, while staying politically correct, isn't always going to happen.]

#11 KevinM1

KevinM1

    Snarkimus Prime

  • Moderators
  • 5,189 posts
  • LocationNew Hampshire, USA

Posted 30 July 2013 - 12:33 PM

Exactly.  Would it make more sense if it looked like:

foreach ($_POST as $key => $value) {
    if (is_array($value)) {
        $temp = $value;
    } else {
        $temp = trim($value);
    }
}

?

 

Because that's what the ternary operator is actually doing:

 

(condition) ? if true : if false

 

So, in this case, you're looping through all of $_POST blindly, and can't tell from the outset if you're dealing with a single entry or a collection of them, which is what that ternary operator checks for.



#12 .josh

.josh

    .josh

  • Administrators
  • 14,807 posts

Posted 30 July 2013 - 01:48 PM   Best Answer

A form can have any number and type of elements(text fields, radio buttons, checkboxes, hidden fields, dropdowns, etc.).

$_POST is an array of all the form elements and their values that was submitted. Depending on how complex the form is, $_POST can be anything from an array with a single element, to a multi-dimensional array.

For example, with a simple form like this:
 
<?php
echo "<pre>";print_r($_POST);echo "</pre>";
?>
<form action='' method='post'>
  <input type='text' name='email' />
  <input type='submit' name='submit' value='submit' />
</form> 
$_POST will look like this:
Array
(
    [email] => foo@bar.com
    [submit] => submit
)
But with a more complex form, like one with checkboxes:
 
<?php
echo "<pre>";print_r($_POST);echo "</pre>";
?>
<form action='' method='post'>
  <input type='text' name='email' /> <br/>
  <input type="checkbox" name="animals[]" value="dog" />dog <br/>  
  <input type="checkbox" name="animals[]" value="cat" />cat <br/>  
  <input type="checkbox" name="animals[]" value="mouse" />mouse <br/>  
  <input type='submit' name='submit' value='submit' />
</form>
$_POST will look like this:
Array
(
    [email] => foo@bar.com
    [animals] => Array
        (
            [0] => dog
            [1] => mouse
        )

    [submit] => submit
)
So from this, is_array($_POST['email']) would be false, since that is just a string "foo@bar.com". But is_array($_POST['animals']) would be true.

Checking whether or not the posted value is an array may or may not be relevant to the actual code example in the book; you'd have to post the form code from the book for us to determine that.

Did I help you? Feeling generous? Donate to me! || Donate to phpfreaks!
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#13 Bert1455

Bert1455

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 30 July 2013 - 06:19 PM

Thanks guys, I really appreciate it and this website is extremely helpful. 






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com