<?php
$fact_BB = array("[start]", "[mid]", "[end]");
$fact_HTML = array("<tr><td class='FactsTableTDOne'><p>", "</p></td><td class='FactsTableTDTwo'><p>", "</p></td></tr>");
$str_Facts = str_replace($fact_BB, $fact_HTML, $row['facts']);
echo $str_Facts;
?>
Is it possible to switch between 2 $fact_HTML?
1. $fact_HTMLone = "code";
2. $fact_HTMLtwo = "code";
3. $fact_HTMLone = "code";
4. $fact_HTMLtwo = "code";
5. $fact_HTMLone = "code";
etc. etc.
Sure. With $fact_HTML[0], $fact_HTML[1], $fact_HTML[n] etc. you can access your $fact_HTML array. Using modulo of 2 you can always access every 2nd (or first and second) elements of the array.
To check if the element is even or odd you can use:
if ($n % 2 == 0) {
//even element
} else {
//odd element
}
Also you can use Modulo 2 ($n % 2) as n to iterate through the array in the same way. You can also combine both variants.
$count = 10; //number of facts
for ($n = 0; $n < $count; $n++) {
$fact_HTML[$n % 2] = $fact;
}
What you want to achieve is a replace of some strings. I'd suggest a solution like this:
<?php
$str_Facts = $row['facts'];
$replacements = array( "[start]" => "<tr><td class='FactsTableTDOne'><p>",
"[mid]" => "</p></td><td class='FactsTableTDTwo'><p>",
"[end]" => "</p></td></tr>" );
foreach ($replacements as $repkey => $repval) {
$str_Facts = str_replace($repkey,$repval,$str_Facts);
}
echo $str_Facts;
?>
If you want to go on with your approach, you'd loop through the arrays (you have to ensure that the both arrays have the same number of elements).
<?php
$str_Facts = $row['facts'];
for ($i=0;$i<count($fact_BB);$i++) {
//if you want to switch every uneven, do this:
if ($i%2!=0) continue;
$str_Facts = str_replace($fact_BB[$i],$fact_HTML[$i],$str_Facts);
}
echo $str_Facts;
?>
Related
I have a problem with my code. what I want to do is to delete an item from the array when it has been called meaning that, I want every output to be different. I want to use it to rotate proxy and there are over 150 proxies in the array. Here's an example of my code.
for ( $i = 1; $i < 2; $i++ )
{
// If the array_history is empty, re-populate it.
if (empty($array_history))
$array_history = $array;
// Select a random key.
$key = array_rand($array_history, 1);
// Save the record in $selected.
$selected = $array_history[$key];
// Remove the key/pair from the array.
unset($array_history[$key]);
// Echo the selected value.
echo $selected;
}
How can I do this or is a for loop not suitable for this? thanks in advance.
What you want to do is spread access over 150 proxies. In this case, it is not really necessary to do it randomly. You can just go through the array.
<?php
$array = [0, 1, 2, 3, 4, 5, 6];
for ( $i = 1; $i < 20; $i++ )
{
echo getNext($array) . '<br>';
}
function getNext (&$array) {
$e = next($array); // Every time next element is selected. Each output is different.
if ($e)
return $e;
else
return reset($array);
}
?>
This seems like a good application for a generator. This one takes an array of proxy addresses and loops over the array in random order, shuffling the array each time it starts the loop again.
function get_proxy($proxies) {
$i = 0;
$len = count($proxies);
while (true) {
if ($i == 0) shuffle($proxies);
yield $proxies[$i];
$i = ($i + 1) % $len;
}
}
To use this, you would do something like this:
$proxies = array('10.0.0.4', '192.168.0.1', '10.1.0.1');
$i = 0;
foreach (get_proxy($proxies) as $proxy) {
echo "$proxy\n";
$i++;
// stop otherwise infinite loop
if ($i == 9) break;
}
Note that since the generator has an infinite loop in it, the external foreach loop will also be infinite, and so needs a way to break out (I've used a simple counter in this case).
Sample output for the above code:
10.1.0.1
10.0.0.4
192.168.0.1
192.168.0.1
10.1.0.1
10.0.0.4
10.1.0.1
192.168.0.1
10.0.0.4
Demo on 3v4l.org
If a generator doesn't suit your code structure, you could use a function with static variables to return a new proxy on each call:
$proxies = array('10.0.0.4', '192.168.0.1', '10.1.0.1');
function get_proxy($proxies) {
static $i = 0, $keys;
if (!isset($keys)) $keys = array_keys($proxies);
if ($i == 0) shuffle($keys);
$proxy = $proxies[$keys[$i]];
$i = ($i + 1) % count($keys);
return $proxy;
}
for ($i= 0; $i < 9; $i++) {
echo get_proxy($proxies) . "\n";
}
Sample output for this code:
10.1.0.1
10.0.0.4
192.168.0.1
192.168.0.1
10.1.0.1
10.0.0.4
10.0.0.4
192.168.0.1
10.1.0.1
Demo on 3v4l.org
When you define an array in php such as
<?php
$alphabet = array(a, b, c)
?>
Your trying to look for the elements in the array. The element list always starts at a count of 0. So to call individual elements count from left to right starting at 0.
<?php
#a
echo $alphabet[0];
#b
echo $alphabet[1];
#c
echo $alphabet[2];
?>
The above section should yield a result of abc because there are no breaks.
For loops are really handy for going through the entire array and running checks, error analysis or even math as examples.
I've changed tho cede slightly, to me it reads as code that will take a selection of items, pick one at random, discard the item, and then pick again until none are left. If there are none left, copy the original array and start again.
Currently your code loops once. I've extended the loop to 4 iteratons here. And upon each random selection, am storing that random key in a history array. You can then refer to that history later in your code.
<?php
$array =
[
'beatle' => 'John',
'stone' => 'Mick',
'floyd' => 'Syd'
];
for ($history = [], $i = 1; $i < 5; $i++)
{
if (empty($buffer))
$buffer = $array;
$key = array_rand($buffer, 1);
$history[] = $key;
echo $buffer[$key], "\n";
unset($buffer[$key]);
}
var_export($history);
Example output:
Syd
Mick
John
Syd
array (
0 => 'floyd',
1 => 'stone',
2 => 'beatle',
3 => 'floyd',
)
Referring to the history array above:
echo $array[$history[3]];
Would output Syd.
Adapting and encapsulating the above in a class. This will do the same (but not store the history of picks), taking an item from an array at random and remove until there are no more items in the array, and then replenish the list and so on:
class RandomProxies
{
const PROXIES =
[
'proxy1' => 'foo.example.com',
'proxy2' => 'bar.example.com',
'proxy3' => 'baz.example.com',
];
private $buffer;
public function getProxy() {
if (empty($this->buffer))
$this->buffer = self::PROXIES;
$key = array_rand($this->buffer);
$proxy = self::PROXIES[$key];
unset($this->buffer[$key]);
return $proxy;
}
}
$randomiser = new RandomProxies;
foreach(range(1,4) as $n) {
echo $randomiser->getProxy(), "\n";
}
Example output:
foo.example.com
baz.example.com
bar.example.com
foo.example.com
hi i have created watch points in this columns 1,2,3,4,5.....100 will come
Example: 1,2,4,5,34,56,100
from above 3 is missing first this number should return
$watchPoints = $videoWatchedData['watch_points'];
$fetArray = explode(",",$watchPoints); //unsorted 2,4,5,100,56,1,34
i want to sort the above one like this 1,2,4,5,34,56,100 and return first missing number.
What i have tried:
$sortFetchedArraysort = sort($fetArray ); //ksort,rosrt no one is working
$Expected = 1;
foreach ($sortFetchedArraysort as $Number){
if ($Expected != $Number) {
break;
}
$Expected++;
}
$percentageCount = $Number; // first missing number in my case output should return 3
exit;
Two problem i am facing one is sort not working second first missing number is not trturning.
Try this few code, check the live demo.
<?php
sort($array = explode(',', "10,1,2,4,5,6,25,36,75,100"));
print_r(current(array_diff(range(1, 100), $array)));
Hope this simple one, will be helpful for you. In your post you are sorting $fetArray but there is no need, you can check it like this.
<?php
ini_set('display_errors', 1);
$array=range(1,100);//your columns
//you should sort like this, but it is not at all required
$fetArray=array(2,4,5,100,56,1,34);
sort($fetArray);
//looping over array in which we are trying to find
foreach($array as $value)
{
//at the moment your that value is not present in array we will break from loop
if(!in_array($value, $fetArray))
{
break;
}
}
//at the moment we break from loop we will get the value which is not present
echo $value;
$watchPoints = "10,1,2,4,5,6,25,36,75,100";
$fetArray = explode(",", $watchPoints);
sort($fetArray);
for ($i = 0; $i < sizeof($fetArray); $i++) {
if ($fetArray[$i] != $i + 1) {
$missing = $i + 1;
break;
}
}
print($missing);
I have an array that goes from '00:00:00' to '23:59:59', something like this ['00:00:00', '00:00:01' ... '23:59:59'].
I need to write a function to reduce the array length into n items but always keeping the first and the last element.
An example:
reduce_into($array, 3) -> ['00:00:00', '12:00:00', '23:59:59']
Note that the array must be "balanced", that means that when I reduce it into 3 elements it will return the first, the one in the middle and the last one.
Here's the code:
function getnewarray($t,$i)
{
$newArr[0] = $t[0];
$a = 1;
$masterdivby = $divby = count($t) / ($i-1);
$ni = $i-2;
while($a <= $ni)
{
$newArr[$a] = $t[$divby];
$divby = $masterdivby + $divby;
$a++;
}
$newArr[$i] = $t[count($t) - 1];
return $newArr;
}
?>
I have an array which is structured like this:
funActivities(array)
0(array)
Activity(array)
id 4
name walks
1(array)
Activity(array)
id 5
name cycling
2(array)
Activity(array)
id 6
name sand pit
and then another like:
activities
0(array)
id 4
name walks
1(array)
id 6
name sand pit
I want to compare the two arrays and end up with an array which only contains the activities from the 1st array which don't appear in the 2nd array. So in this case I'd end up with just cycling in the array. It's in the first array, but not the second.
Whats the best way to do that?
i made a php function that works for you...
i hope this can help. of course there are some things i could do better but for this szenario it works
<?php
$funActivities[0]['Activity']['id'] = 4;
$funActivities[0]['Activity']['name'] = "walks";
$funActivities[1]['Activity']['id'] = 5;
$funActivities[1]['Activity']['name'] = "cycling";
$funActivities[2]['Activity']['id'] = 6;
$funActivities[2]['Activity']['name'] = "sand pit";
$activities[0]['id'] = 4;
$activities[0]['name'] = "walks";
$activities[1]['id'] = 6;
$activities[1]['name'] = "sand pit";
function compareArray($needle,$haystack)
{
$tmpArray = $haystack;
foreach($needle as $n)
{
$s1 = $n['id'].$n['name'];
$count = 0;
foreach($haystack as $h)
{
$s2 = $h['Activity']['id'].$h['Activity']['name'];
if( $s1 == $s2)
{
unset($tmpArray[$count]);
}
$count++;
}
}
return array_values($tmpArray);
}
$arr = compareArray($activities,$funActivities);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW