Comparing 2 arrays with different lengths - php

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

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

PHP - Stop need to create hundreds of variables

I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)

Foreach into PHP array

I've this these array values :
$cart_item['addons'][0]['price'] = '52';
$cart_item['addons'][1]['price'] = '34';
$cart_item['addons'][2]['price'] = '12';
......
....
I want that each values are at 0 like :
$cart_item['addons'][0]['price'] = '0';
$cart_item['addons'][1]['price'] = '0';
$cart_item['addons'][2]['price'] = '0';
....
...
So I try this code :
for ($i=0; $i > 0 ; $i++) {
$cart_item['addons'][$i]['price'] = '0';
}
But it does not work. Thanks for your help !
Try this simple solution:
$count=count($cart_item['addons']);
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
If your array is big enough, putting count() function inside for loop is being a crazy coconut. It will be much, much slower. Please use the count outside the loop:
$count = count($cart_item['addons'])
for($i=0; $i<$count;$i++ ){
$cart_item['addons'][$i]['price'] = '0';
}
You have to loop more often to achive this:
foreach($cart_item['addons'] as &$addons {
foreach($addons as &$addon) {
$addon['price'] = 0;
}
}
You can iterate over $cart_item['addons'], like so:
foreach ($cart_item['addons'] AS $key => &$value) {
$value['price'] = 0;
}
(Your code does not get executed, because $i is never changed and so is never > 0)
Also note that you need to use the reference (&$value) when changing the array in foreach loop.
There are three parts to your for loop: for(counter | test | action){}. It might be useful for you to look at this guide about for loops. You initialise your variable:
$i = 0;
then you do a logical check (the test part):
$i > 0;
If we substitute the the variable ($i) for the value it holds (0) we get:
0 > 0
which will never be true and thus you will never get to the final part (action) of the for loop:
$i++;
Instead you could make it loop until it has moved through your entire array like this:
$elementCount = count(cart_item['addons']);
for($i=0; $i < $elementCount; $i++){
$cart_item['addons'][$i]['price'] = '0';
}
Each time it loops we add one to $i until we reach the stopping condition where $i is no longer less than the number of items in the array.
It's also worth noting that PHP has a number of functions that help working with arrays.

Issue with getting data when traversing through an array PHP with a variable

I asked a similar question earlier but I couldn't get a clear answer to my issue. I have a function "isParent" that gets 2 pieces of data. Each 1 of the 2 gets a string separating each value with a , or it just gets a plain int and then checks if the first value given is a parent of the second.
I pull the 2 bits of data in and explode them but when I go through my nested for loop and try to test
$toss = $arr1[$i];
print_r($toss);
It comes up blank. I have no idea what the issue is: Here is the full code of the function...
function isParent($parent, $child)
{
$parentArr = explode(',', $parent);
$childArr = explode(',',$child);
//Explode by Comma here. If array length of EITHER parentArr or childArr > 1 Then throw to an Else
if(count($parentArr) <= 1 && count($childArr) <= 1) //If explode of either is > 1 then ELSE
{
$loop = get_highest_slot(15);
for($i = $loop; $i > 0; $i--)
{
$temp = get_membership_from_slot($i,'id_parent','id_child');
if($temp['id_parent'] == $parent && $temp['id_child'] == $child)
{
return 1;
}
}
}
else //set up a for loop in here so that you traverse each parentArr value and for each iteration check all child values
{
$i = count($parentArr);
$c = count($childArr);
for(;$i >=0;$i--) //Loop through every parent
{
for(;$c >=0;$c--)
{
echo '<br>$i = ';
print_r($i);
echo '<br><br>Parent Arr at $i:';
$toss = $parentArr[$i];
echo $toss;
echo '<br>';
print_r($childArr);
echo '<br><br>';
if(isParent($parentArr[$i],$childArr[$c])) //THIS CAUSES AN INFINITE YES! Learn how to pull an array from slot
{
return 1;
}
}
}
}
return 0;
}
You are missing some code for the slot procedures. Apart from that, you probably need to use a different variable for the inner for loop. because $c will be 0 after the first iteration of $i.
Thanks for the help! The issue was in the recursive call back to the top of the function. It was tossed empty slots and when comparing 2 empty slots it returned a false positive. A quick !empty() check fixed it.

Comparing an array against itself

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.

Categories