PHP: Add multiple entries to array - php

I have a string and a value.
I am exploding the string which returns a few results to a list.
I want to add each of those items from the list to an array, with the same value assigned to each string.
Here is what I have so far:
$count = 3;
$amount = 2500;
$value = ceil ($amount / $count);
$string = "String1, String2, String3, ";
$strings = explode(", ", $string);
I want to run a foreach that puts $strings and $value into an array together.
Any pointers?

You can simply use:
$combo = array_fill_keys( $strings , $value );
// var_dump( $combo ); // to check you got it right.
This takes the values in your $strings array and uses them as the keys for the new $combo array, setting the same value for each key.

Related

Replace array value with more than one values

I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);

Saving values from a variable to an array

I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4

Order array of strings based on a portion of each string

How can i order an array from this:
$unordered_array = array('11196311|3','17699636|13','11196111|0','156875|2','17699679|6','11196237|7','3464760|10');
To this
$ordered_array = array('11196111', '156875', '11196311', '17699679','11196237','3464760', '17699636');
The number after the "|" defines the position, and the array needs to be ordered from lower to higher, and remove the position number in the final array.
Why you don't try by yourself ? You take more writing your answer than doing it by yourself.
$array = array();
foreach($unordered_array as $value) {
$value = explode('|', $value);
$array [$value[1]]= $value[0];
}
ksort($array);
$ordered_array = array_values($array);
var_dump($ordered_array);

PHP match string in array, modify string and then create new array

I'm not sure how to better phrase my question, but here is my situation.
I have an array like the following:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
I need to loop through this array and try to match the first portion of each string in the array
e.g.
$id = "222222";
$rand_number = "999888";
if ($id match the first element in string) {
fetch this string
append "999888" to "122874|876394|120972"
insert this string back to array
}
So the resulting array becomes:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-999888|122874|876394|120972", "333333-Name3-122874|876394|120972");
Sorry if my question appears confusing, but it really is pretty difficult for me to even grasp some of the required operations.
Thanks
Try this:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
// Loop over each element of the array
// For each element, $i = the key, $arr = the value
foreach ($temp_array as $i => $arr){
// Get the first characters of the element up to the occurrence of a dash "-" ...
$num = substr($arr, 0, strpos($arr, '-'));
// ...and check if it is equal to $id...
if ($num == $id){
// ...if so, add $random_number to the back of the current array element
$temp_array[$i] .= '|' . $rand_number;
}
}
Output:
Array
(
[0] => 111111-Name1-122874|876394|120972
[1] => 222222-Name2-122874|876394|120972|999888
[2] => 333333-Name3-122874|876394|120972
)
See demo
Note: As Dagon pointed out in his comment, your question says appends, but your example shows the data being prepended. This method appends, but can be altered as necessary.
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strpos.php
You could also using some exploding in this case too:
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as &$line) {
// ^ reference
$pieces = explode('|', $line); // explode pipes
$first = explode('-', array_shift($pieces)); // get the first part, explode by dash
if($first[0] == $id) { // if first part is equal to id
$first[2] = $rand_number; // replace the third part with random
$first = implode('-', $first); // glue them by dash again
$line = implode('|', array($first, implode('|',$pieces))); // put them and glue them back together again
}
}
echo '<pre>';
print_r($temp_array);
crude answer - its going to depend on the expected values of the initial ids. if they could be longer or shorter then explode on the hyphen instead of using substr
$temp_array = array("111111-Name1-122874|876394|120972","222222-Name2-122874|876394|120972","333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
foreach($temp_array as $t){
if(substr(0,6,$t)==$id){
$new[] = $t.'|'.$rand_number;
}else{
$new[] = $t;
}
}
Another version using array_walk
$temp_array = array("111111-Name1-122874|876394|120972", "222222-Name2-122874|876394|120972", "333333-Name3-122874|876394|120972");
$id = "222222";
$rand_number = "999888";
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
$parts = explode('-', $value); // Split parts with '-' so the first part is id
if ($parts[0] == $param['id']){
$parts[2]="{$param['rand_number']}|{$parts[2]}"; //prepend rand_number to last part
$value=implode('-',$parts); //combine the parts back
}
},$params);
print_r($temp_array);
If you just want to append The code becomes much shorter
$params = array('id'=>$id, 'rand_number'=>$rand_number);
array_walk($temp_array, function(&$value, $key, $param){
// here check if the first part of the result of explode is ID
// then append the rand_number to the value else append '' to it.
$value .= (explode('-', $value)[0] == $param['id'])? "|{$param['rand_number']}" : '';
},$params);
Edit: Comments added to code.

Insert into php array after certain value?

I have a string like this,
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4
And if I need to add another value to the string I do this:
$sidePanel = explode('&', $_SESSION['sidePanel']);
array_push($sidePanel, 'sidePanel[]=3');
$sidePanel = implode('&', $sidePanel);
Which returns this:
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4&sidePanel[]3
Now how can I make it so that it will always insert after the array 'sidePanel[]=2' when I explode it at &?
I do not want it in numerical order although this example will return it in numerical order, as the string can change to be in any order.
I cannot use array_splice as I understand this uses the key of the array, and as the position of sidePanel[]=2 can change it will not always be the same.
You can indeed use array_splice, but you have to find the position of your insertion point first:
$sidePanelArr = explode( '&', $_SESSION['sidePanel'] );
// find the position of 'sidePanel[]=2' in array
$p = array_search( 'sidePanel[]=2', $sidePanelArr );
// insert after it
array_splice( $sidePanelArr, p+1, 0, 'sidePanel[]=3' );
$sidePanelSt = implode( '&', $sidePanelArr );
You could also splice the string right into your original string without exploding and re-imploding.
The function substr_replace() is your friend:
$sidePanelSt = $_SESSION['sidePanel'];
// find the position of 'sidePanel[]=2' in string
// (adding '&' to the search string makes sure that 'sidePanel[]=2' does not match 'sidePanel[]=22')
$p = strpos( $sidePanelSt.'&', 'sidePanel[]=2&') + strlen('sidePanel[]=2' );
// insert after it (incl. leading '&')
$sidePanelSt = substr_replace( $sidePanelSt , '&sidePanel[]=3' , $p, 0 );
See : http://codepad.org/5AOXcHPk
<?php
$str = "sidePanel[]=1&sidePanel[]=2&sidePanel[]=4";
$sidePanelArr = explode('&', $str);
$newVal = 'sidePanel[]=3';
$insertAt = 2 ;
$newArr = array_merge(array_slice($sidePanelArr, 0,$insertAt),
array($newVal),
array_slice($sidePanelArr,$insertAt)
);
$sidePanel = implode('&', $newArr);
echo $sidePanel,PHP_EOL ;
?>
You could turn it into an array using parse_str and locate the value you want to insert it after:
// Turn it into an array
$url = parse_str($_SESSION['sidePanel']));
// What value do we want to insert it after
$insert_after = 2;
// The value you want to insert
$sidePanel = 3;
// Find the position of $insert_after
$offset = array_search($insert_after, $url['sidePanel']);
// Slice the array up (based on the value)
$url['sidePanel'] = array_merge(array_slice($url['sidePanel'], 0, $offset),
array($sidePanel),
array_slice($url['sidePanel'], $offset));
// Turn it back into a string
echo http_build_query($url);

Categories