php loop with variable changing simplified - php

pretty sure my title needs to be fixed but anyhow, i have this loop. background info, i have 36 input "types" that need to be inserted 1 by 1. if the value has something.. set to a variable, if not set it to NULL.
MY question is, is there a loop i can perform to do this without listing 36 of these things.
using php version 5.2.17
if (!empty($_POST['type1'])){
$type1 = $_POST['type1'];
}
else
$type1 = NULL;
if (!empty($_POST['type2'])){
$type2 = $_POST['type2'];
}
else
$type2 = NULL;
if (!empty($_POST['type3'])){
$type3 = $_POST['type3'];
}
else
$type3 = NULL; // to 36...
php/html
<?php
for ($i = 1; $i < 37; $i++){
echo "Type$i:<input name='type$i' type='text' size='20' maxlength='35' /><br />";
}
?>
edit: I don't want to use an array.

To actually define all those variables $type1, $type2 etc, use "variable variables":
for ($i = 1; $i < 37; $i++) {
$varname = "type$i";
if (! empty($_POST[$varname])) {
$$varname = $_POST[$varname];
}
else {
$$varname = NULL;
}
}
Others suggest using an array instead (and in principle I agree), but this is an actual answer to the question.

Question was updated to not use an array. Will keep it here for someone looking for an answer that can use an array.
You could add the $_POST array to a predefined array of values storing the result in another array. For example:
<?php
$defaults = array(
"type1" => NULL,
"type2" => NULL,
"type3" => NULL,
"type4" => NULL
// etc
);
$_POST = array(
"type1" => 1,
"type2" => "foo"
);
$types = $_POST + $defaults;
print_r($types);
Which results in the array:
Array
(
[type1] => 1
[type2] => foo
[type3] =>
[type4] =>
...
)
Then for your html loop:
for ($i = 1; $i < 37; $i++){
echo "Type$i:<input name='" . $types["type" . $i] . "' type='text' size='20' maxlength='35' /><br />\n";
}
It is important to note that this is slightly different than using a check with empty.

Use an array on both the php and form inputs.
$type = array();
for ($i = 1; $i <= 36; $i++) {
if (isset($_POST['type'][$i])){
$type[$i] = $_POST['type'][$i];
}
}
HTML/PHP
<?php
for ($i = 1; $i <= 36; $i++){
echo "Type$i:<input name='type[$i]' type='text' size='20' maxlength='35' /><br />";
}
?>

Just an example with an array named $post.
$post = array(
'type1' => 'one',
'name' => 'test',
'type3' => 'three'
);
$matches = preg_grep ('^type[0-9]^', array_keys($post));
foreach ($matches as $val) {
$$val = $post[$val];
}
var_export($type1);

Use array for this
$i = 0;
$myinputs = 36;
while($i<$myinputs){
$i++;
if(empty($_POST['type'.$i.''])){
$type[$i] = $_POST['type'.$i.''];
}else{
$type[$i] = null;
}
}
print_r($type);

Related

How to create an array with X amount of values, based on a string?

I am trying to create an array based on the value of a string (integer), for example:
// my string
$dogs = '2';
// my array
$dogs_array = array(
[0] => 'Dog 1',
[1] => 'Dog 2'
);
So if the string was 4 there would be 4 items in the array. Is this possible? If so how can this be done?
Thanks in advance.
$i = 1;
$dogs_count = (int)$dogs;
while ($i <= $dogs_count) {
$dogs_array[] = 'Dog ' . $i++;
}
print_r($dogs_array);
<?php
// my string
$dogs = '5'; //initialize your variable
$dogsArray = array(); // initialize an empty array
for($i =1; $i <= $dogs; $i++)
{
array_push($dogsArray, 'Dog '.$i);
}
var_dump($dogsArray);
?>
$count = (int) $dogs;
$dogs_array = [];
for($i = 0;$count>$i; $i++){
$dogs_array[$i] = "Dogs ".$i;
}
print_r($dogs_array);

Duplicate values multi array

As the title states I'm searching for a unique solution in multi arrays. PHP is not my world so I can't make up a good and fast solution.
I basically get this from the database: http://pastebin.com/vYhFCuYw .
I want to check on the 'id' key, and if the array contains a duplicate 'id', then the 'aantal' should be added to each other.
So basically the output has to be this: http://pastebin.com/0TXRrwLs .
Thanks in advance!
EDIT
As asked, attempt 1 out of many:
function checkDuplicates($array) {
$temp = array();
foreach($array as $k) {
foreach ($array as $v) {
$t_id = $k['id'];
$t_naam = $k['naam'];
$t_percentage = $k['percentage'];
$t_aantal = $k['aantal'];
if ($k['id'] == $v['id']) {
$t_aantal += $k['aantal'];
array_push($temp, array(
'id' => $t_id,
'naam' => $t_naam,
'percentage' => $t_percentage,
'aantal' => $t_aantal,
)
);
}
}
}
return $temp;
}
How about this code, each 'aantal' has initial value of 1, and duplicated id have their aantal incremented mutually, and duplicated id's are not suppressed. As your first array index is 0-based numeric, so we don't consider this dimension as a hash array, but rather a normal array.
UPDATED: id's can be duplicated 2 times, 3 times, 4 times, ...
<?php
//
// duplicate elements are not suppressed:
//
function checkDuplicates($xarr) {
//
$xarrDone = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
$xarrDone[$i] = true;
for($j = 0; $j < $n1; $j++)
{
$xarr[$hasId0[$j]]['aantal'] += $n1;
$xarrDone[$hasId0[$j]] = true;
}
}
}
}
//
return $xarr;
}
//
// duplicate elements are suppressed:
//
function checkDuplicates2Unique($xarr) {
//
$xarrDone = array();
$xarrNew = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
for($j = 0; $j < $n1; $j++)
{
$xarrDone[$hasId0[$j]] = true;
}
}
$xarrNew[] = $xarr[$i];
$xarrDone[$i] = true;
}
}
//
return $xarrNew;
}
//
// main test:
//
$xarr0 = array(
array(
'id' => 6
, 'naam' => 'Aardmonnik'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel 8 Bruin'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 3
, 'naam' => 'IV Saison'
, 'percentage' => '6,5%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => '3 Schténg'
, 'percentage' => '6,00%'
, 'aantal' => 1
)
);
//
echo "<pre>
Original:
";
print_r($xarr0);
//
echo "</pre>";
//
$xarr = checkDuplicates($xarr0);
//
echo "<pre>
Modified:
";
print_r($xarr);
//
$xarr = checkDuplicates2Unique($xarr0);
//
echo "<pre>
Modified Unique:
";
print_r($xarr);
//
echo "</pre>";
?>
?
checkDuplicates(): keep duplicated id's.
checkDuplicates2Unique(): delete duplicated id's to get unique id's.
Try using php's array_unique function: http://php.net/manual/en/function.array-unique.php
It should work on arrays
Otherwise (if you can sort the array -> faster):
<?php
$db = array(....); // your data
function remove_duplicates (array $arr) {
usort($arr, function ($a, $b) {
return $a['id'] < $b['id'];
});
$result = array();
$last_id = null;
$last_index = -1;
for ($i=0; $i<count($arr); ++$i) {
if ($arr[$i]['id'] == $last_id) {
result[$last_index]['aantai'] += 1;
continue;
}
$last_id = $arr[$i]['id'];
$last_index = count($result);
$result[] = $arr[$i];
}
return $result;
}
?>
Only loop over the input once, then copy the element when the id is new, else add the value:
function checkDuplicates($array) {
$temp = array();
// Only loop through the input once
foreach($array as $k) {
// Use the id as array index
if (array_key_exists($k['id'], $temp) {
// Only check id and add aantal?
$temp[$k['id']['aantal'] += $k['aantal'];
} else {
// Copy the element to the output
$temp[$k['id']] = $k;
}
}
return $temp;
}
Depending on your further code, you might need to reset the array indices by sort() or something.
Edit: sorry I forgot an index to $temp - the aantal field schould be correct now.

Json array in php code

I need to use Json array in the php code.
The problem is that I'm in a for loop and need to separate the array in 2 and then want to merge it. but so far it didn't work.
I use it to have a graph (jqxChart).
Here is my code
for($i = 0; $i < $nb; $i++){
if ($i%2 == 1){
$time[$i] = (hexdec($hour[$i]));
$orders1[] = array(
'OrderDate' => $time[$i],
);
}else{
$hour[$i] = $hour[$i] + 1;
$orders2[] = array(
'ProductName' => $hour[$i],
);
}
}
$orders[] = array_merge_recursive( $orders1[], $orders2[] );
}
echo json_encode($orders);
Thanks
try this code,
$orders1 = array();
$orders2 = array();
for($i = 0; $i < $nb; $i++){
if ($i%2 == 1){
....
$temp1 = array(
'OrderDate' => $time[$i],
);
array_push($orders1, $temp1);
}else{
....
$temp2 = array(
'ProductName' => $hour[$i],
);
array_push($orders2, $temp2);
}
}
}
$orders = array_merge( $orders1, $orders2 );
echo json_encode($orders);
Remove the square brackets. Instead of:
$orders[] = array_merge_recursive($orders1[], $orders2[]);
^^ ^^ ^^
Just put:
$orders = array_merge($orders1, $orders2);

How can we find the Duplicate values in array using php?

I would like to know, how can we detect the duplicate entries in array...
Something like
$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1","192.168.1.4") ;
I want to get the number of Duplicity used in array (C class unique).
like this
192.168.1.1 = unique
192.168.2.1 = Duplicate
192.168.3.1 = unique
192.168.4.1 = unique
192.168.2.1 = Duplicate
192.168.2.1 = Duplicate
192.168.10.1 = unique
192.168.2.1 = Duplicate
192.168.11.1 = unique
192.168.1.4 = Duplicate (Modified)
I tried this code like this style
$array2 = array() ;
foreach($array as $list ){
$ips = $list;
$ip = explode(".",$ips);
$rawip = $ip[0].".".$ip[1].".".$ip[2] ;
array_push($array2,$rawip);
}
but i am unable to set the data in right manner and also unable to make the loop for matching the data.
modified values
Thanks
SAM
Try this : this will give you the count of each value
$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1") ;
$cnt_array = array_count_values($array)
echo "<pre>";
print_r($cnt_array);
$res = array();
foreach($cnt_array as $key=>$val){
if($val == 1){
$res[$key] = 'unique';
}
else{
$res[$key] = 'duplicate';
}
}
echo "<pre>";
print_r($res);
use array_unique($array) function.
it will give you below output.
Array
(
[0] => 192.168.1.1
[1] => 192.168.2.1
[2] => 192.168.3.1
[3] => 192.168.4.1
[6] => 192.168.10.1
[8] => 192.168.11.1
)
And total duplicate count must be :
array_count_values($array)
Try this, hope it'll work
$FinalArray=array();
$arrayLen=count($array);
for($i=0; $i<$arrayLen; $i++)
{
if(!in_array($array[$i],$FinalArray))
$FinalArray[]=$array[$i];
}
Now in $FinalArray you got all the unique ip
Try this:
for ($i = 0; $i < count($array); $i++)
for ($j = $i + 1; $j < count($array); $j++)
if ($array[$i] == $array[$j])
echo $array[$i];
use in_array() function to check value is or not in array
<?php
$output ='';
$array = array(0, 1, 1, 2, 2, 3, 3);
$isArraycheckedvalue = array();
for ($i=0; $i < sizeof($array); $i++)
{
$eachArrayValue = $array[$i];
if(! in_array($eachArrayValue, $isArraycheckedvalue))
{
$isArraycheckedvalue[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated no <br/>";
}
else
{
$isArraycheckedvalue[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated yes <br/>";
}
}
echo $output;
?>
find the Duplicate values in array using php
function array_repeat($arr){
if(!is_array($arr))
return $arr;
$arr1 = array_unique($arr);
$arr3 = array_diff_key($arr,$arr1);
return array_unique($arr3);
}

Is there a simpler way to change a single array value?

What I'm trying to do is default the $names array value to it's parallel $urls value if a $_POST[] value of $names is empty. (This is based on the assumption that an empty $_POST[] will return empty, someone please correct me if I'm wrong).
Here's my code:
$urls = array(1 => $_POST['url_1'], 2 => ['url_2'], 3 => $_POST['url_3'], 4 => $_POST['url_4'], 5 => $_POST['url_5']);
$names = array(1 => $_POST['name_1'], 2 => ['name_2'], 3 => $_POST['name_3'], 4 => $_POST['name_4'], 5 => $_POST['name_5']);
if(empty($names[1])) { $names[1] = $_POST['url_1']; }
if(empty($names[2])) { $names[2] = $_POST['url_2']; }
if(empty($names[3])) { $names[3] = $_POST['url_3']; }
if(empty($names[4])) { $names[4] = $_POST['url_4']; }
if(empty($names[5])) { $names[5] = $_POST['url_5']; }
I thought about using a foreach() loop, but I don't really see how that would work, as each individual array value e.g. $names[1] would have to be set to $urls[1] if empty.
Any advice, comments or other information would be very much appreciated :)!
for ($i = 1; $i <= 5; $i++) {
$names[$i] = !empty($_POST['name_' . $i]) ? $_POST['name_' . $i] : $_POST['url_' . $i];
}
for ($i = 1; $i <= 5; $i++) {
if (empty($names[$i])) {
$names[$i] = $_POST['url_' . $i];
}
}
But keep in mind that you also need to check if $_POST['url_' . $i'] exists too with additional isset() check
foreach ($names as $k=>$v){
if(empty($v)){
$names[$k] =$urls[$k];
// or $names[$k] = $_POST['url_' . $k'];
}
}
$urls = array(1 => $_POST['url_1'], $_POST['url_2'], $_POST['url_3'], $_POST['url_4'], $_POST['url_5']);
$names = array(1 => $_POST['name_1'], $_POST['name_2'], $_POST['name_3'], $_POST['name_4'], $_POST['name_5']);
for ( $c = 1; $c <= 5; $c++ )
{
if(empty($names[$c]))
{
$postKey = 'url_'.$c;
$names[$c] = $_POST[$postKey];
}
}

Categories