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

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];
}
}

Related

How to add string into array in PHP?

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo

PHP endless loop, why?

Here is my code. I don't understand why am I in endless loop.
I think $check has to stop the loop when I make unique random values for my array.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$check;
do
{
foreach($foo as &$val)
{
$val = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
The problem is that the first time through the loop there are some duplicates, so array_unique() reduces the array from 4 elements to 1, 2, or 3. The foreach loop can never make the array bigger again, because it's only looping over the elements that currently exist in the array. So once the array shrinks, it will never grow back to 4 elements, and $check != 4 will always be true.
You should get the original keys of the array and use that.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$keys = array_keys($foo);
$check;
do
{
foreach($keys as $i)
{
$foo[$i] = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
DEMO
Personally, I wouldn't do it in a loop with such low entropy as it could take all day to finally match a random set.
A better way would be to generate a range and randomise that, then loop over your array and set the value.
<?php
$rand = range(1, 6);
shuffle($rand);
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$i=0;
foreach ($foo as $key => $value) {
$foo[$key] = $rand[$i];
$i++;
}
print_r($foo);
/*Array
(
[blue] => 1
[black] => 3
[red] => 2
[white] => 5
)
*/
https://3v4l.org/4hPku

php loop with variable changing simplified

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);

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.

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);
}

Categories