filtering out repeats - php

I'm creating a program which goes through data in a array and filter outs any repeats within it and then echos out anything which isn't a repeated piece of data
for ($i = 0; $i < count($urlArray); $i++) {
for ($j = 0; $j < count($urlArray); $j++) {
if($i != $j)
{
if($urlArray[$i] !== $urlArray[$j])
echo $urlArray[$i];
}
}
}
I'm fairly certain there's something wrong but I can't quite spot it, any help with this would be great.

I dont get, how your array is structured, but whats about just array_unique()
$urlArray = array_unique($urlArray);
Or in your case (because you want to echo it
foreach (array_unique($urlArray) as $url) echo $url;
Update:
Sorry, just mixed up two functions :) Of course its array_unique() and not array_filter().

You could use built in function array_unique() to remove duplicate values in array
$result = array_unique($urlArray);
print_r($result);

Related

PHP, array count, two foreach combination

I am solving this not understandable script, I even don't know where from to start. Maybe someone will help me.
I got two arrays example:
$a1 = array(1,2,3 ...);
$a2 = array(4,5,6 ...);
what I need is that first array will divide all values by itsel
for this I would like to get script which will work like this (array values can be savet to the same name because will be anyway continue with them, can be new variable, in this example I use new). In the same way variable can be devidet by itself to get 1 but prefer not to. Example of count.
$b1 = array([0]/[1], [0]/[2], [0]/[3], [1]/[0], [1]/[2], [1]/[3], [2]/[0], [2]/[1], [2]/[3], [3]/[0], [3]/[1], [3]/[2]);
$b2 = array( *** The same like $b1 ***);
On the end will go foreach to write values to table, this I solved already
echo "<table><tr>";
foreach($b1 as $key1 => $val1){
foreach($b2 as $key2 =>$val2){
echo "<td>".$key1.$key2."<br/>".val1*val2."</td>";
}
echo "</tr><tr>";
}
echo "</tr></table>"
Anyone can give me a help to this issue?
To do the division of each element is relatively simple. You do it with 2 for loops. The one thing you have to bear in mind, however, is avoiding division by 0. Do you have elements that could be 0? If so, do you want the division result to be 0, or the same as the numerator? the code I show below assumes the latter:
function getDivided($array) {
$length = count($array);
$return = [];
for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < $length; $j++) {
if ($i === $j) continue;
//the following assumes that the values in the array are never < 1 Change this according to your needs
$return[] = $array[$i] / max($array[$j], 1);
//Another option is to use a conditional
$return[] = $array[$j] === 0 ? $array[$i] : $array[$i] / $array[$j];
}
}
return $return;
}
$b1 = getDivided($a1);
$b2 = getDivided($a2);

PHP skip for loop Iteration based on a query result set

Lets say for example I have a result set from a MySQL query that has produced values: 3,5,10,11 and so forth...
I would like to iterate through a for loop in PHP but exclude the any iteration that would equal any number in results of my MySQL query.
As it stands I currently have:
for($i = 1; $i <= $num_rows; $i++)
{
if($i == 3 or $i == 5)
{
continue;
}
//Rest of loop...
As you will all appreciate hard coding these values is very time consuming and not very efficient. If any one could help it would be greatly appreciated.
If you can gather automatically those values you are currently hard coding, you can use in_array($search, $array[, $strict])
Like this :
$bypass = array(3, 5);
for($i = 1; $i <= $num_rows; $i++)
{
if( in_array($i, $bypass) )
{
continue;
}
// rest of the loop
}
PS : I prefer much more the "Dont Panic" answer, which doesn't use too many loops. (in_array will loop through the array to find your value). See his answer : https://stackoverflow.com/a/38880057/3799829
If your query results are returned as an array you can use
if(in_array($i, $results)) to do a check of $i against the results
Add your values into an array while you fetch your query results. I used PDO here for example, but you should be able to adapt it to whichever database extension you're using:
while ($row = $stmt->fetchObject()) {
$exclude[$row->value] = true;
// whatever else you're doing with the query results
}
If you use the values as keys in the array of things you want to skip, checking for them in your for loop should be more efficient than using in_array.
for($i = 1; $i <= $num_rows; $i++) {
if (isset($exclude[$i])) continue;
// rest of loop

Using an index twice in PHP

I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";

Looping through an explode() in php weird output

I'm getting a very weird results when trying to loop through a comma delimited list in PHP.
It sometimes only outputs a few of them and there seems no logical reason to why it doesn't loop through all of them, and I can't for the life of me figure out what's actually causing it.
My code is:
//pids = &pids=1,2,3,6,7,9
$pids = $_GET['pids'];
$photoIdArray = explode(",", $pids);
for($i = 0; $i <= count($photoIdArray); $i++) {
foreach($photoIdArray as $j){
if($i == $j){
echo "{$j}";
}
}
}
// result = 1236
This is just for testing so there is im not checking the inputs to prevent exploits and what not at the moment.
Any help would be appreciated.
Thanks!
Combining 2 loop for and foreach is overkill for something like this
Try using only foreach
$pids = "1,2,3,6,7,9";
$photoIdArray = explode(",", $pids);
foreach($photoIdArray as $value)
{
echo $value;
}
Output
123679
It is because you are looping through your values and check if $i is the same as the value. You should check
if ($photoIdArray[$i] == $j) {
instead of
if ($i == $j) {
This is the reason it didn't work, but you should still use Baba's method.
I agree with Dusan, Baba & Co., but to answer the actual question:
Nothing weird happens here. i loops from 0 to 6 (though the array has only indices 0..5), and you compare i with the VALUES of the array, which range from 1 to 9. Of course, only the values 1 to 6 are matched, because i never exceeds 6.
EDIT: Asad and Sietse were faster.

These Loops are Not Working Properly

I have been working with the same loop for a couple days now, and it still won't work the way I want it to. I have tried both for, foreach and while and it still refuses to work.
The code that won't work is simply:
if(!empty($_POST['submit'])){
$d = count($_POST['deleteT']);
for ($pi = 1; $pi <= $d; $pi++) {
echo "Banned ".$_POST['deleteT'][$pi]."</br>";
}
}
If deleteT has two values: 'Bob' and 'Joe' it will print:
Banned Joe
Banned
Does anyone have any insight into why this is going on?
Start your loop index with $pi = 0; and only loop while $pi < $d.
I think one of your problems is in your count statement, then with the <= condition in the for loop.
If you use count(), then just use <. Example:
$c = count($my_array);
for ($i = 0; $i < $c; $i++) {
// do stuff
}
That said, an easier way to iterate over an array is with foreach. Like this:
foreach ($my_array as $key => $val) {
// do stuff with $val or $key
}

Categories