PHP Assistance with empty() in a loop - php

Let's say I wanted to check to see if a variable is empty and then do something... I can do this:
if ( empty($phone) ) { $phone = 'Not Provided'; }
But I want to do that for a bunch of items. So I'm thinking an array and a loop, so something like this:
$optionalFieldsArray = array($phone, $address, $city, $state, $zip);
foreach ($optionalFieldsArray as $value) {
//what goes here????
}
Is this foreach a resonable way to do it, where I could check if $phone, $address, $city, etc. are empty and assign the "Not Provided" string to it when it is?
If so, can someone help me with the syntax that goes inside that loop?

you can do like this:
<?php
$required_vars = array( 'phone', 'address', 'city', 'state', 'zip' );
foreach( $required_vars as $required_var ) {
if( empty( $$required_var ) )
$$required_var = 'Not Provided'; // $$var -> variable with name = value of $var
}
?>
check the above code yourself. then only you can understand how it works. because it is confusing concept.

$optionalFieldsArray = array('phone'=>$phone, 'address'=>$address, 'city'=>$city, 'state'=>$state, 'zip'=>$zip);
foreach ($optionalFieldsArray as $key => $value) {
if ( empty($value) ) { $optionalFieldsArray[$key] = 'Not Provided'; }
}
echo "<pre>";
print_r($optionalFieldsArray);
echo "</pre>";

I'd say something like -
$optionalFieldsArray = array($phone, $address, $city, $state, $zip);
foreach ($optionalFieldsArray as $key => $value) {
if ( empty($optionalFieldsArray[$key]) ) {
$optionalFieldsArray[$key] = 'Not Provided';
}
}

Combine the two code examples you provided, and use strings as keys in the optional array:
$optional = array(
'phone' => $phone,
'address' => $address,
'city' => $city,
'state' => $state,
'zip' => $zip,
);
foreach ($optional as $type => $value) {
if ($value == null) {
echo "The {$type} field is empty!<br>";
}
}

$optionalFieldsArray = array($phone, $address, $city, $state, $zip);
foreach($optionalFieldsArray as $k => $v) {
// you could check for !empty here if you wanted too
$optionalFieldsArray[$k] = empty($v) ? 'Not Provided' : $v;
}
print_r($optionalFieldsArray);
Input Vars:
$phone = "1234567899";
$address = "";
$city = "";
$state = "";
$zip = "";
Output:
Array ( [0] => 1234567899 [1] => Not Provided [2] => Not Provided [3] => Not Provided [4] => Not Provided )

Related

simply adding code to php function

I want to create a php function with the following code but when I add this to a function it stops working:
Code works:
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
Code Doesnt work:
function metaData() {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData(); // NULL
$home, $about, and $details are all out of scope in your function. You need to pass them as parameters to that function for them to be available to the function itself.
function metaData($home, $about, $details) {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);
foreach($arr as $key => $value){
if($url == $key) {
echo $value;
}
}
}
metaData($home, $about, $details);

How can I return a PHP $_POST array as string that is usable as a name attribute?

Question:
I have an array of post values that looks like:
$_POST['children'] = array(
[0]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[1]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[2]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
)
);
// and so on
I have a script set up in my my view functions that checks for old input, and repopulates the values in the case that the form does not validate. I need to find a way to return the above array as a series of key/value pairs i.e.
'children[0][fname]' = 'name'
'children[0][mname]' = 'mname'
'children[0][lname]' = 'lname'
// ... and so on for all fields
Ideally, I would like this to work with an array of any depth, which makes me think I need some sort of recursive function to format the keys. I am having a terrible time getting my head around how to do this.
What I have tried
I have been working with the following function:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
$result[$prefix . $key .''] = $value;
}
}
return $result;
}
This gets me somewhat close, but isn't quite right. It returns the following when I feed it my $_POST array
[children[1]fname] => test
[children[1]mname] => test
[children[1]lname] => test
[children[1]dob] =>
// Expecting: children[1][fname] => test
// ...
Or is there potentially an easier way to accomplish this?
What ended up working for me:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
}
}
return $result;
}
it wasn't accounting for the return value of the last call of the recursive function being a scalar value. The addition of these this if/else statement seems to have resolved it.
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}

Echo key value from array returned from a function in PHP

Sorry if this is a bit of a noob question, am still a beginner on php....
I need to echo the Country key from an array returned from a function.
I have tried various way of trying to get the value I am wanting from the array, but each time do not get the results I want.
I want to set the 'country' value from the returned array to a variable to do an if argument on the value. Please help...
sample of what Im trying to do below -
<?php
$country = get_shipping_address()['country']
if ( $country=="GB" ) {
do this;
}
?>
Below is the function -
function get_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
$joined_address = array();
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
}
}
return $this->shipping_address;
}
Your issue is that you're doing this in your function:
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
What that does, is makes a string with all the values of your array. Example:
derp, derp, derp, derp, derp, derp
What you want is to return the $address variable.
return $address;
Making your function look like this:
function get_shipping_address() {
$address = array();
if (!$this->shipping_address) {
if ($this->shipping_address_1) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address;
}
Thanks Darren, ( and everyone else that commented )
That done the trick.
I have created a new function and changed it to only return the value I am needing, as I just need to know the country value.
So have changed the function as below.
Thanks for the help!!
function get_my_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address['country'];
}

custom validation class only testing last element

I have been trying to make a custom validation class, but it is bothering me that it only is test thing last element it sees. I need it to test everything I put into it.
<?php
class Valid {
function validate(array $args){
$errors = NULL;
//********************************
//Find each key validation.
//********************************
foreach ($args as $key => $value){
//*********************************
//Check for letters only, a-z, A-Z.
//*********************************
if ($key == 'letters'){
$letters = preg_match('/^\pL+$/u', $value) ? TRUE : FALSE;
$letters_value = $value;
$letters_array[] = $letters;
}
//*********************************
//Check for numbers only, 0-9.
//*********************************
if ($key == 'numbers'){
$numbers = preg_match('/^[0-9]+$/', $value) ? TRUE : FALSE;
$numbers_value = $value;
$numbers_array[] = $numbers;
}
//*********************************
//Check for vaild email address.
//*********************************
if ($key == 'email'){
$email = filter_var($value, FILTER_VALIDATE_EMAIL) ? TRUE : FALSE;
$email_value = $value;
$email_array[] = $email;
}
//*********************************
//Check for empty string.
//*********************************
if ($key == 'empty'){
$empty_it = (trim($value) == FALSE) ? TRUE : FALSE;
$empty_array[] = $empty_it;
}
}
//********************************
//Check if you failed letters only.
//********************************
if ( count($letters_array) != count(array_filter($letters_array)) ) $errors .= 'You can only enter letters a-z or A-Z.<br />';
//********************************
//Check if you failed numbers only.
//********************************
if ( count($numbers_array) != count(array_filter($numbers_array)) ) $errors .= 'You can only enter numbers 0-9.<br />';
//*************************************
//Check if you failed email validation.
//*************************************
if ( count($email_array) != count(array_filter($email_array)) ) $errors .= 'You must enter a vaild e-mail address.<br />';
//*************************************
//Check if you empty string.
//*************************************
if ( count($empty_array) != count(array_filter($empty_array)) ) $errors .= 'You must enter a value for each required field.<br />';
//********************
//Display the errors.
//********************
if ($errors) echo '<h3>Oops..</h3>'. $errors; var_dump($args); die;
}
}
And then I call it like this:
$Validate->validate( array('empty' => $display_name, 'empty' => $password, 'empty' => $password_again,
'empty' => $gender, 'empty' => $month, 'empty' => $day, 'empty' => $year, 'email' => $email, 'letters' => $gender,
'numbers' => $month, 'numbers' => $day, 'numbers' => $year) );
But my result is this:
array(4) { ["empty"]=> string(4) "2013" ["email"]=> string(0) "" ["letters"]=> string(0) "" ["numbers"]=> string(4) "2013" }
Any help?
You cannot reuse keys in arrays. The last key - value pair will overwrite all the previous.
Write an array like:
$Validate->validate(array(
'empty' => array($display_name, $password, $password_again, $gender, $month, $day, $year, $email),
'letters' => array($gender, $month),
'numbers' => array($day, $year).
));
and parse it appropriately:
if (isset($args["key"])) {
foreach ($args["key"] as $value) {
// ...
}
}
// and this for every method to check
array('empty' => $display_name, 'empty' => $password, 'empty' => $password_again,
'empty' => $gender, 'empty' => $month, 'empty' => $day, 'empty' => $year, 'email' => $email, 'letters' => $gender,
'numbers' => $month, 'numbers' => $day, 'numbers' => $year)
This is not a valid hash. Keys must be unique.
You could, however, pass something like this:
array(
array('empty' => $display_name),
array('empty' => $password),
array('empty' => $password_again),
array('empty' => $gender), ...
)
and modify your loop appropriately.
Documentation: http://php.net/manual/en/language.types.array.php
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

UPDATE an array using PDO

I'm creating a multi-step form for my users. They will be allowed to update any or all the fields. So, I need to send the values, check if they are set and if so, run an UPDATE. Here is what I have so far:
public function updateUser($firstName, $lastName, $streetAddress, $city, $state, $zip, $emailAddress, $industry, $password, $public = 1,
$phone1, $phone2, $website,){
$updates = array(
'firstName' => $firstName,
'lastName' => $lastName,
'streetAddress' => $streetAddress,
'city' => $city,
'state' => $state,
'zip' => $zip,
'emailAddress' => $emailAddress,
'industry' => $industry,
'password' => $password,
'public' => $public,
'phone1' => $phone1,
'phone2' => $phone2,
'website' => $website,
);
Here is my PDO (well, the beginning attempt)
$sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
Basically, how can I create the UPDATE statement so it only updates the items in the array that are not NULL?
I thought about running a foreach loop like this:
foreach($updates as $key => $value) {
if($value == NULL) {
unset($updates[$key]);
}
}
but how would I write the prepare statement if I'm unsure of the values?
If I'm going about this completely wrong, please point me in the right direction. Thanks.
First of all, use array_filter to remove all NULL values:
$updates = array_filter($updates, function ($value) {
return null !== $value;
});
Secondly, bind parameters, that makes your live a lot easier:
$query = 'UPDATE table SET';
$values = array();
foreach ($updates as $name => $value) {
$query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip
$values[':'.$name] = $value; // save the placeholder
}
$query = substr($query, 0, -1).';'; // remove last , and add a ;
$sth = $this->dbh->prepare($query);
$sth->execute($values); // bind placeholder array to the query and execute everything
// ... do something nice :)
The below can be optimized:
$i = 0; $query = array();
foreach($updates as $key => $value) {
if ($value != NULL) {
$query[] = "{$key} = :param_{$i}";
$i++;
}
}
if (! empty($query)) {
$finalQuery = implode(",", $query);
$sth = $this->dbh->prepare('UPDATE user SET ' . $finalQuery);
$i = 0;
foreach($updates as $key => $value) {
if ($value != NULL) {
$sth->bindParam(':param_'.$i, $value, PDO::PARAM_STR);
$i++;
}
}
}

Categories