Simplifying an array in PHP - php

I have the following Arrays which I need to define in PHP which I've done in a very basic way:
$ch1 = array("A-MTP-1-1","A-MTP-1-2","A-MTP-1-3","A-MTP-1-4");
$ch2 = array("A-MTP-1-5","A-MTP-1-6","A-MTP-1-7","A-MTP-1-8");
$ch3 = array("A-MTP-1-9","A-MTP-1-10","A-MTP-1-11","A-MTP-1-12");
$ch4 = array("A-MTP-2-1","A-MTP-2-2","A-MTP-2-3","A-MTP-2-4");
$ch5 = array("A-MTP-2-5","A-MTP-2-6","A-MTP-2-7","A-MTP-2-8");
$ch6 = array("A-MTP-2-9","A-MTP-2-10","A-MTP-2-11","A-MTP-2-12");
$ch7 = array("A-MTP-3-1","A-MTP-3-2","A-MTP-3-3","A-MTP-3-4");
$ch8 = array("A-MTP-3-5","A-MTP-3-6","A-MTP-3-7","A-MTP-3-8");
$ch9 = array("A-MTP-3-9","A-MTP-3-10","A-MTP-3-11","A-MTP-3-12");
But I was thinking there must be a simple way of writing this rather than writing out each one but not sure where to start, Would someone be able to point me in the right direction to simplifying this PHP as I will also be repeating it for the above but with B instead of A for each one.

Use range() , array_chunk and extract to get this done
<?php
for ($i = 1; $i <= 3; $i++) { # Pass 3 as you need three sets
foreach (range(1, 12) as $val) { # 1,12 again as per your requirements
$arr[] = "A-MTP-$i-" . $val;
}
}
foreach (array_chunk($arr, 4) as $k => $arr1) { # Loop the array chunks and set a key
$finarray["ch" . ($k + 1)] = $arr1;
}
extract($finarray); # Use the extract on that array so you can access each array separately
print_r($ch9); # For printing the $ch9 as you requested.
Demo
OUTPUT : (Illustration for $ch9 part alone)
Array
(
[0] => A-MTP-3-9
[1] => A-MTP-3-10
[2] => A-MTP-3-11
[3] => A-MTP-3-12
)
After doing that , you can use array_chunk to split the array to length of 4.

Related

How to output different values from an array

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

How to split evenly and oddly a string to form an array of even and odd results OK Like

I have a php string formed by images and corresponding prices like OK Like
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
I know that if I do:
$myArray = explode(',', $myString);
print_r($myArray);
I will get :
Array
(
[0] => ddb94-b_mgr3043.jpg
[1] => 3800
[2] => 83acc-b_mgr3059.jpg
[3] => 4100
)
But How could I split the string so I can have an associative array of the form?
Array
(
"ddb94-b_mgr3043.jpg" => "3800"
"83acc-b_mgr3059.jpg" => "4100"
)
Easier way to do like below:-
<?php
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$chunks = array_chunk(explode(',', $myString), 2); //chunk array into 2-2 combination
$final_array = array();
foreach($chunks as $chunk){ //iterate over array
$final_array[trim($chunk[0])] = trim($chunk[1]);//make key value pair
}
print_r($final_array); //print final array
Output:-https://eval.in/859757
Here is another approach to achieve this,
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100,test.jpg,12321";
$arr = explode(",",$myString);
$temp = [];
array_walk($arr, function($item,$i) use (&$temp,$arr){
if($i % 2 != 0) // checking for odd values
$temp[$arr[$i-1]] = $item; // key will be even values
});
print_r($temp);
array_walk - Apply a user supplied function to every member of an array
Here is your working demo.
Try this Code... If you will receive all the key and value is equal it will work...
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$myArray = explode(',', $myString);
$how_many = count($myArray)/2;
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $myArray[$i];
$value = $myArray[$i+1];
// store it here
$arra[$key] = $value;
}
print_r($arra);

how to add letters of the name as array elements in php?

i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}

How to add variables that are passed on through the URL to an array?

<?php
$i = $_GET['i'];
echo $i;
$values = array();
while ($i > 0)
{
$expense = $_GET['expense_' + i];
$amount = $_GET['amount_' + i];
$values[$expense] = $amount;
i--;
print_r($values);
}
?>
i represents the number of sets of variables I have that have been passed through from the previous page. What I'm trying to do is add the expenses to the amounts and put them in an array as (lets just say for this example there were 3 expenses and 3 amounts) [expense_3 => amount_3, expense_2 => amount_2, expense_1 => amount_1]. The names of the variables are successfully passed through via the url as amount_1=50, amount_2=50, expense_1=food, expense2=gas, etc... as well as $i, I just dont know how to add those variables to an array each time.
Right now with this code I'm getting
4
Array ( [] => ) Array ( [] => ) Array ( [] => ) Array ( [] => )
I apologize if I'm not being clear enough, but I am pretty inexperienced with PHP.
The syntax error you're getting is because you're using i instead of $i - however - that can be resolved easily.
What you're looking to do is "simple" and can be accomplished with string-concatenation. It looks like you're attempting this with $_GET['expense'] + i, but not quite correct.
To properly build the parameter name, you'll want something like $_GET['expense_' . $i], here you can see to concatenate strings you use the . operator - not the + one.
I'm going to switch your logic to use a for loop instead of a while loop for my example:
$values = array();
for ($i = $_GET['i']; $i > 0; $i--) {
$expense = $_GET['expense_' . $i];
$amount = $_GET['amount_' . $i];
$values[$expense] = $amount;
}
print_r($values);
This is following your original logic, but it will effectively reverse the variables (counting from $i down to 1). If you want to count up, you can change your for loop to:
$numVariables = $_GET['i'];
for ($index = 1; $index <= $numVariables; $index++) {
$expense = $_GET['expense_' . $index];
...
Or just serialize the array and pass it to the next site, where you unserialize the array
would be much easier ;)

Create / add up array with switch statements

For readability and perfomance reasons, I'd like to build up an array with a switch statement instead of if-statements.
Consider the following if-statement:
$size = 2;
$array = array();
if($size >= 1) { array_push($array,'one','foo'); }
if($size >= 2) { array_push($array,'two','bar','barista'); }
if($size >= 3) { array_push($array,'three','zoo','fool','cool','moo'); }
It basically counts up from 1 to $size, it might be more readable and most likely a lot faster with a switch-statment...but how do you construct that ??
$step = 2;
$array = array();
switch($step)
{
case ($step>1): array_push($array,'one','foo');
case ($step>2): array_push($array,'two','bar','barista');
case ($step>3): array_push($array,'three','zoo','fool','cool','moo');
}
I tried leaving out the break, which didn't work - as the manual says:
In a switch statement, the condition is evaluated only once[...].
PHP continues to execute the statements until the end of the switch
block, or the first time it sees a break statement.
Anyway, anyone got an idea how to build up such an array with a switch-statement ??
Surely what you want can be achieved much more easily using
$array=range(1,$size);
Based on further coments and subsequent edits, something like:
$baseArray = $array(array('one'),
array('two','twoA'),
array('three','threeA','threeB'),
array(),
array('five'),
);
$step=2;
$array = array_slice($baseArray,0,$step);
and then flatten $array
Well, a switch statement would look like:
edit: the above doesn't work - let me take a look.
but in this example, you could just do:
$size = 2;
$array = range(1, $size); // Array ( [0] => 1 [1] => 2 )
$valuesIWant = array(1=>'one','two','three','four');
$array = array();
for ($i = $step - 1; $i > 0; $i--) $array[] = $valuesIWant[$i];
$array = array_reverse($array);
So if $step is 2, you get:
Array
(
[0] => one
)
...and if it is 4, you get:
Array
(
[0] => one
[1] => two
[2] => three
)

Categories