How can we use a condition inside a foreach loop - php

The following foreach query is inserting only values in ['options']['Colors'] and not those in ['options']['Color'] ???
Updated Question:
if (!is_array($value['options']['Colors'])) {
$value['options']['Colors'] = array($value['options']['Colors']);
}
if (!is_array($value['options']['Color'])) {
$value['options']['Color'] = array($value['options']['Color']);
}
if(isset($value['options']['Colors'])) {
$colorArr = $value['options']['Colors'];
} else if(isset($value['options']['Color'])) {
$colorArr = $value['options']['Color'];
}
foreach ($colorArr as $colors) {
$stmt->execute(array(':pid' => $PID, ':colors' => $colors));
}

You can't do this as this way... it does not make a sense. what exactly do you want to do ?
if you want check the existence of a value in array you could use in_array function like this:
if(in_array("someValue", $someArray)) {
// Do something ...
}

We can not use OR in foreach loop. Instead we can use if statement to verify and then can go ahead like below:
if(isset($value['media']['options']['Colors'])) {
$colorArr = $value['media']['options']['Colors'];
} else if(isset($value['media']['options']['colors'])) {
$colorArr = $value['media']['options']['colors'];
}
foreach ($colorArr as $colors) {
// You can use $colors now where you want
}

If you really insist on having the array such that either key may be used, I suggest you convert all to lower case before using them
foreach($value['media']['options'] as &$key => $value){
if($key == 'Colors'){
$key = 'colors';
}
}
Then try using the array as before, but without the need for the OR statement checking for 'Colors'

you could merge the arrays then loop, be careful of key conflicts though. can one option have both a "color" and a "Color" in which case it can get messy really fast, which one do you use, the first, the second, both, none?
$colors = array_merge ($value['media']['options']['Colors'], $value['media']['options']['colors'] );
foreach($colors as $color ){
}

Related

PHP - elegant way to check if assoc array value has a subarray?

Is there any elegant way to check if
$review['passenger'] has any $review['passenger']['*']?
Try with is_array(). It will check if it is an array or not -
if(is_array($review['passenger'])) {
// is an array
}
Or if you want to check if some key is present or not then -
if(array_key_exists('key', $review['passenger'])) { ... }
I believe Danius was using "['*']" to reference "one or more sub-arrays", instead of specifying it as "the" sub-array.
About his question, the only way to verify if a specific KEY of your array has sub-arrays is checking its sub-items, one by one, to identify if any one of them is an array.
It may not be "elegant", but it is definitively functional:
function has_array($arr) {
$has_array = false;
foreach ($arr as $item):
if (is_array($item)):
$has_array = true;
break;
endif;
endforeach;
return $has_array;
}
Simply call the function this way:
$result = has_array($review['passenger']);
I hope it helps.
You can use array_key_exists:
$array = array(
"passenger" => array(
"*" => "ok"
)
);
if(array_key_exists('*', $array['passenger'])){
echo "ok";
} else {
echo "not ok";
}

How to generate a longer isset() statement in PHP?

I have an interesting question today. Lets say I have an array of form fields:
array('field1', 'field2', 'field3');
I would basically want to generate an if statement which check if all of the provided fields are exists or not.
So something like this:
function ($array){
$stm = '';
foreach($array as $key){
$stm .= 'isset($_POST['.$key.']) && ';
}
if (rtrim($stm, ' && ')){
echo 'Fields are exists.';
}
}
The problem with the above function is that it takes the created statement as a String and not a variable, so it always exsits. Is there any way that I can generate something like this, which would work?
You're thinking about this the wrong way. If I understood correctly, you have an array of values, that are also POST keys, and you want to check if all of them are set. In this case I'd do something like:
function isset_multiple($array){
foreach($array as $post_key){
if(!isset($_POST[$post_key])) // if one of them is not set, return false
return false;
}
return true; // none of the foreach loops returned false, so all must be set
}
What you can do is check if array keys are set by using variable names, for example
$keyName = "field1";
if ( isset($_POST[$keyName]) === true ) { /* ... */ }
The example above can be implemented in a foreach loop.
Just execute the isset and count:
function ($array){
$count = 0;
foreach($array as $key){
if (isset($_POST[$key]) $count++;
else // you can already exit here...
}
if (count($array) === $count){
echo 'All fields exist.';
}
}
Try this..
function arrayHasKeys(array $array, array $keys)
{
return !((bool) array_diff_key($array, $keys));
}
var_dump(arrayHasKeys($_POST, array('field1', 'field2', 'field3')));
Its quite simple and reusable. Its not a good practice to use global vars inside a function.

If true use foreach loop, else use while

I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}

iterate through array, number of keys is variable, the first value being processed differently

Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)

PHP arrays - a 'set where key=?' type function?

Is there a built in php function that allows me to set a value of an array based on a matching key? Maybe i've been writing too much SQL lately, but i wish I could perform the following logic without writing out nested foreach array like the following:
foreach($array1 AS $k1 => $a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$array[$k1]['new_key'] = $a2['value'];
}
}
}
Is there a better way to do this? In SQL logic, it would be "SET array1.new_key = x WHERE array1.id = array2.id". Again, i've been writing too much SQL lately :S
When I need to do this, I use a function to first map the values of one array by id:
function convertArrayToMap(&$list, $attribute='id') {
$result = array();
foreach ($list as &$item) {
if (is_array($item) && array_key_exists($attribute, $item)) {
$result[$item[$attribute]] = &$item;
}
}
return $result;
}
$map = convertArrayToMap($array1);
Then iterate through the other array and assign the values:
foreach ($array2 AS $a2) {
$id = $a2['id'];
$map[$id]['new_key'] = $a2['value'];
}
This are less loops overall even for one pass, and it's convenient for further operations in the future.
This one is fine and correct
foreach(&$array1 AS &$a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$a1['new_key'] = $a2['value'];
}
}
}

Categories