Comparing an array against itself - php

I am currently a bit stuck in finding out how to compare these variables against eachother, I have 24 dropdown selections with 24 options to choose from within each one, I then post them to the PHP page. What is the easiest, most efficient way of comparing each of these values against each other to check that each option that is chose is different from each other as none of the 24 options can be the same. I know that an array is the way forward with this, just not sure on how to compare them.
Any help is much appreciated.
$id = $_POST[trackid];
$pos1 = $_POST[pos1];
$pos2 = $_POST[pos2];
$pos3 = $_POST[pos3];
$pos4 = $_POST[pos4];
$pos5 = $_POST[pos5];
$pos6 = $_POST[pos6];
$pos7 = $_POST[pos7];
$pos8 = $_POST[pos8];
$pos9 = $_POST[pos9];
$pos10 = $_POST[pos10];
$pos11 = $_POST[pos11];
$pos12 = $_POST[pos12];
$pos13 = $_POST[pos13];
$pos14 = $_POST[pos14];
$pos15 = $_POST[pos15];
$pos16 = $_POST[pos16];
$pos17 = $_POST[pos17];
$pos18 = $_POST[pos18];
$pos19 = $_POST[pos19];
$pos20 = $_POST[pos20];
$pos21 = $_POST[pos21];
$pos22 = $_POST[pos22];
$pos23 = $_POST[pos23];
$pos24 = $_POST[pos24];

Given an array you could try array_unique function
count($original_array) != count(array_unique($original_array))
Alternative solution with array_count_values
count(array_count_values($original_array)) = count($original_array)
There are lot of way to do that (e.g. a for loop), it just depends from your exact needs.

Firstly, you should be adding quotes around your array indices rather than using barewords which should be raising warnings:
$pos1 = $_POST['pos1'];
To copy the pos* values out of $_POST, you should use a loop:
$pos = array();
for ($i = 1; $i <= 24; ++$i) {
$pos["pos$i"] = $_POST["pos$i"];
}
To make sure there are no duplicates, use array_unique and see if the two arrays have the same length:
if (count(array_unique($pos)) == count($pos)) {
# pos contains no duplicates
}

Just do an array_unique on it. First you'll need to put those POST vars into an array instead of splitting them up.
$pos = array();
for ($i = 1; $i <= 24; $i++)
{
$pos["pos$i"] = $_POST["pos$i"];
}
$unique = array_unique($pos);
if (count($unique) == 24)
{
// all good!
}
else
{
// bad!
}

can you more explicit? if none of them can be the same, than what is the problem?
considering that you actually can select the same option more than once or you just want to protect from attacks, than you can put them into an array, and then use the array_unique function.

Related

php not able to get array value

I have this problem where I can't get the value from the array in the for loop but I can access it in the while loop.
I can't seem to find a answer online, so help would be much appreciated.
while ($pos = strpos($logTxt, $char, $pos))
{
$t++;
$pos += strlen($char);
$positions[$t] = $pos;
}
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[2];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
I think that this could be pretty easily fixed by using a foreach loop instead of a for loop, because it is an array.
foreach($positions as $position) {
$beginLine = $lastEndLine;
$endLine = $position;
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
If you want to use a for loop still, I believe your problem is you are only referencing the 3rd position of the array (Key 2, as arrays start at 0), not what the loop is pointing to. You could fix it by doing this
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[$i];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Your $endLine always has third element from array, because of $positions[2]. Try changing it to $positions[$i]
You base problem is using constant index in $positions[2]. But your 1st line in for loop $beginLine = $lastEndLine; will always fail because $lastEndLine is not defined yet. You can use smth like
// beginLine // endLine
$textToEcho = substr($logTxt, $positions[$i-1], $positions[$i]);
of course you need $positions[-1] set to 0 before your first loop or smth like this (it's not clear what's happening before)
UPD I've tried your code and concluded
it will not work at all if $char is the first occurence in $logTxt
it does the nearly the same as explode() function

How to implode many available to one available using loop for?

How to implode many available to one available using loop for ?
i have many available like
$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;
and then i want to implode to one available
$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,
but i want to using loop for like this
for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}
how can i do ? thank you for every comment ^^
$all_data = implode(',', array($var_1, $var_2, ..., $var_11));
Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.
For the for loop you're trying to write, see the PHP documentation on Variable Variables.
$all_data = '';
for ($i = 1; $i < 12; $i++) {
$all_data .= ${'var_'.$i} . ',';
}

Comparing 2 arrays with different lengths

I have 2 arrays that I wish to compare and update the score if a match is found:
One_array[0] = bla
One_array[1] = blabla
One_array[2] = blablabla
Two_array[0] = bla
Two_array[1] = blabla
Score_array[0] = 10
Score_array[1] = 15
Score_array[2] = 1
Now here's the php code for doing the comparison:
$count = count($One_array);
$Score = 0; //Initialize score
for($i=0;$i<=$count;$i++){
for($j=0;$j<=$count;$j++){
if(isset($Two_array[$i]) == $One_array[$j]){
$Score = $Score + $Score_array[$j];
}
}
}
I get the following error:
Undefined offset: 2
On the line $Score = Score+$Score_array[$j];
Please assist, I also tried to use isset on this line, it didn't work
The two loops need different limits, because the arrays are different sizes.
$count1 = count($One_array);
$count2 = count($Two_array);
$Score = 0; //Initialize score
for($i=0;$i<$count2;$i++)
{
for($j=0;$j<$count1;$j++)
{
if($Two_array[$i] == $One_array[$j])
{
$Score = $Score + $Score_array[$j];
}
}
}
With this, you don't need to use isset().
You should be able to use the array_diff() function in PHP http://php.net/manual/en/function.array-diff.php instead of creating a compare function on your own.
Well, the error is pretty self explanatory. The $Score_array does not have the index 2 set.
Do a var_dump of the array and look at the output to make sure it actually contains what you believe it to contain.
You have made a lot of mistakes in your code with $i and $j, take a better look on them ;)
By the way you should use array_diff instead of reinventing the wheel :)
Use this code :
$count = count($One_array);
$Score = 0; //Initialize score
for($i=0;$i<=$count;$i++)
{
for($j=0;$j<=$count;$j++)
{
if(isset($Two_array[$i]) && isset($One_array[$j]) && $Two_array[$i]==$One_array[$j])
{
$Score = $Score + $Score_array[$j];
}
}
}
your problem was the if part

How to sort it better?

I have 2 arrays, both are multidimensional with same number of elements and same values, which are on different positions (those values are actually ID-s from my database, so one ID appears only once). How can I sort second array with values which are in first array?
For example - if first array looks like:
$array1[0][0] = 1;
$array1[0][x] = it doesn't matter what's here
$array1[1][0] = 4;
$array1[1][x] = it doesn't matter what's here
$array1[2][0] = 3;
$array1[2][x] = it doesn't matter what's here
...
how to sort second array so it would have same values as array1 on indexes [0][0], [1][0], [2][0], etc.
How I could solve problem is:
$i=0
while ($i < (count($array1)-2)){ // * check down
$find_id = $array1[$i][0];
// here I need to search for index of that ID in other array
$position = give_index($find_id, $array2);
// swapping positions
$temp = array2[$i][0];
$array2[$i][0] = $array2[$position][0];
$array2[$position][0] = $temp;
// increasing counter
i++;
}
function give_index($needle, $haystack){
for ($j = 0, $l = count($haystack); $j < $l; ++$j) {
if (in_array($needle, $haystack[$j][0])) return $j;
}
return false;
}
*There is only -2 because indexes start from 0 and also for the last element you don't need to check since it would be automatically sorted by last iteration of while-loop.
I don't find this solution good as I think that this is quite simple issue (maybe it's not even correct). Is there easier way in PHP that I'm missing?
This is the most efficient way I can think of:
function swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
function find_index($id, $array, $from = 0) {
$index = false;
for ($i = $from, $c = count($array); $i < $c; $i++) {
if ($array[$i][0] == $id) {
$index = $i;
break;
}
}
return $index;
}
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
if ($array1[$i][0] != $array2[$i][0]) {
$fi = find_index($array1[$i][0], $array2, $i);
swap($array2[$i][0], $array2[$fi][0]);
}
}
What changes from yours?
I've defined a swap() function in order to swap any variable. That doesn't cost anything and makes everything look nicer. Also you can reuse that function later if you need to.
In the find_index (give_index in your code) we stop the loop once we find the correct index. Also we avoid the cost of an in_array function call.
We modified the find_index function to start only from the part of the array we haven't checked yet. Leading to a way more efficient way of scan the array.
In the for loop (a while loop was just wrong there) we stored the count of the array once, avoiding multiple calls.
Also we swap the $array2 values only if they are in the wrong place.
Other improvements
If you know anything else of the $array2 array you can make this even more performant. For example if you know that indexes are alternated like in $array1 you can change the main for loop from:
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
to
for ($i = 0, $c = count($array1); $i < ($c - 2); $i+2) {
(notice the $i+2 at the end) And you could do that in the find_index function as well.
Look into usort (http://php.net/manual/en/function.usort.php).
It provides a simple way to sort arrays using a user provided comparison function.

Change the value in one array based on the key of an associative array using PHP

I hope my question adequately describes what I'm after...
Here is the situation. I have the following arrays with values.
categories['t-shirts'] = 10
categories['shorts'] = 11
...
clothing[0] = 't-shirts'
clothing[1] = 'shorts'
...
I want to replace the values in the clothing array (t-shirts, shorts) with the number that matches it from the categories array.
Cheers
foreach($clothing as $key => $val){
if(isset($categories[$val])){
$clothing[$key] = $categories[$val];
}
}
Codepad Example
You can use simple php
categories[clothing[0]] = "some value"
From your question, it looks like
$newArray=array_keys($originalArray);
should do the trick.
$count = count($clothing);
for($i=0; $i<$count; $i++)
$clothing[$i] = (array_key_exists($clothing[$i], $categories))
? $categories[$clothing[$i]] : 0;
for setting the $clothings without any count to 0
$categories = array();
$categories['t-shirts'] = 10;
$categories['shorts'] = 11;
$clothing = array();
$clothing[0] = 't-shirts';
$clothing[1] = 'shorts';
array_walk($clothing,
function(&$value) use($categories) {
if (isset($categories[$value]))
$value = $categories[$value];
}
);
var_dump($clothing);

Categories