I want to change the value of an array without loop-
Example code:
<?php
//current array
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
//result should be looks like this
$ids = array('1113', '1156', '1342', '1132', '1165');
?>
is it possible to do it without any loop?
Instead of the shown string/array function workarounds, you can also just use a PHP built-in to filter the arrays:
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$ids = array_map("intval", $ids);
This converts each entry into an integer, which is sufficient in this case to get:
Array
(
[0] => 1113
[1] => 1156
[2] => 1342
[3] => 1132
[4] => 1165
)
Try this using array_map():
<?php
function remove_end($n)
{
list($front) = explode("_", $n);
return $front;
}
$a = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$a = array_map("remove_end", $a);
print_r($a);
?>
Demo: http://codepad.org/iGJ3cJW2
Possible? Yes:
$ids[0] = substr($ids[0], 0, -2);
$ids[1] = substr($ids[1], 0, -2);
$ids[2] = substr($ids[2], 0, -3);
$ids[3] = substr($ids[3], 0, -2);
$ids[4] = substr($ids[4], 0, -2);
But why do you want to avoid using a loop in this case?
array_map(), but internally it'd still be using a loop.
function $mycallback($a) {
... process $a
return $fixed_value;
}
$fixed_array = array_map('mycallback', $bad_array);
Related
Hi I got the following string:
info:infotext,
dimensions:dimensionstext
and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.
I want to put the info as the key and he infotext as the value into an array like this:
Array {
[info] => infotext
[dimensions] => dimensionstext
}
Demo here
<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));
foreach($array as $v)
{
$o[$v[0]] = $v[1];
}
print_r($o);
You can use array_chunk and array_combine
<?php
$input = 'info:infotext,
dimensions:dimensionstext';
$chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
http://ideone.com/dRtref
I have two arrays:
array(1,2,3,4,5)
array(10,9,8,7,6)
Final array Needed:
array(0=>1:10,1=>2:9,2=>3:8,3=>4:7,4=>5:6)
I can write a custom function which would be quieck enough!! But i wanted to use a existing one so Is there already any function that does this in php? Pass the two input arrays and get the final array result? I read through the array functions but couldn't find any or combination of function that would provide me the result
No built in function but really there is nothing wrong with loop .. Just keep it simple
$c = array();
for($i = 0; $i < count($a); $i ++) {
$c[] = sprintf("%d:%d", $a[$i], $b[$i]);
}
or use array_map
$c = array_map(function ($a,$b) {
return sprintf("%d:%d", $a,$b);
}, $a, $b);
Live Demo
Try this :
$arr1 = array(1,2,3,4,5);
$arr2 = array(10,9,8,7,6);
$res = array_map(null,$arr1,$arr2);
$result = array_map('implode', array_fill(0, count($res), ':'), $res);
echo "<pre>";
print_r($result);
output:
Array
(
[0] => 1:10
[1] => 2:9
[2] => 3:8
[3] => 4:7
[4] => 5:6
)
See: http://php.net/functions
And especially: http://nl3.php.net/manual/en/function.array-combine.php
Also, I don't quite understand the final array result?
Do you mean this:
array (1 = 10, 2 = 9, 3 = 8, 4 = 7, 5 = 6)
Because in that case you'll have to write a custom function which loops through the both arrays and combine item[x] from array 1 with item[x] from array 2.
<?php
$arr1=array(1,2,3,4,5);
$arr2=array(10,9,8,7,6);
for($i=0;$i<count($arr1);$i++){
$newarr[]=$arr1[$i].":".$arr2[$i];
}
print_r($newarr);
?>
Use array_combine
array_combine($array1, $array2)
http://www.php.net/manual/en/function.array-combine.php
Ok, I need an array to be outputted like this:
$sections = array(
5 => $americanFlag,
6 => $americanFlag,
22 => $russianFlag,
23 => $russianFlag,
24 => $russianFlag,
25 => $russianFlag,
);
Ofcourse it is much longer than this.
So, say I have an array like this:
$russian = array(22, 23, 24, 25);
$american = array(5, 6);
And arrays like this:
$americanFlag = 'http://pathtomyAmericanFlag.png';
$russianFlag = 'http://pathtomyRussianFlag.png';
How can I do this quick and easy??
There are probably a few ways to do it. Here's a simple one:
$russian = array_fill_keys($russian, $russianFlag);
$american = array_fill_keys($american, $americanFlag);
$sections = ksort(array_merge($russian, $american));
Assumes you want them sorted by key. If not, just remove the ksort()
$usFlags = array_combine($american, array_fill(0, count($american), $americanFlag);
$ruFlags = array_combine($russian, array_fill(0, count($russian), $russianFlag);
$sections = array_merge($usFlags, $ruFlags);
Should do it. However, I don't know, what you want to achieve, but it seems, that you want to output a flag depending on (I guess) an ID of something?
flags = array_merge(array_flip($russian), array_flip($american));
$helper = function ($id) use (flags) {
return isset($flags[$id]) ? $flags[$id] : null;
}
echo 'http://pathtomy'. ucfirst($helper($id)) . 'Flag.png'; // returns
You can use a multi-dimensional array:
array (
american => array ( [0] => american, [1] american );
russian => array ( [0] => russian, [1] russian );
Is that what you're wanting?
Something similar to this maybe.
$countries = array($russian, $american);
foreach($countries as $country){
foreach($country as $flag) {
echo $sections[$flag];
}
}
Try this
<?php
$russian = array();
$american = array();
foreach($sections as $key=>$value){
if($value == "http://pathtomyRussianFlag.png"){
array_push($russian, $key);
}
elseif($value == "http://pathtomyAmericanFlag.png"){
array_push($american, $key);
}
}
?>
$data1 = "mathews,luks,john,ethan,neil";
$data2 = "80%,60%,78%,55%,62%";
want to combine both like
mathews = 80%
Luks = 60%
John = 78%
etc.... how to do this?? I want print result exactly like Mathews = 80%
http://us.php.net/manual/en/function.array-combine.php
$result = array_combine ( explode ( ',', $data1 ), explode ( ',', $data2 );
to extract:
if you know key name: echo $result ['john'];
if all: foreach ( $result as $key => $value ) { echo $key . ' : ' . $value; }
to gey list of keys: $list = explode ( ',', $data1 ) or $list = array_keys ( $result );
http://us.php.net/manual/en/function.array-keys.php
How about this...?
print_r(array_combine(explode(',',$data1),explode(',',$data2)));
$arr = array_combine(explode(',', $data1), explode(',', $data2));
Or
$names = explode(',', $data1);
$par = explode(',', $data2);
$arr = array();
foreach ($names as $idx=>$name)
{
$arr[$name] = $par[$idx];
}
Use the built in array_combine
You may consider using preg_split to the string:
$names = preg_split("/[,]+/", "mathews,luks,john,ethan,neil");
$percent = preg_split("/[,]+/", "80%,60%,78%,55%,62%");
Then you can use array_combine like many others suggest, or simply use 2 arrays $names and $percent along with the shared index, for example, $names[2] goes along with $percent[2].
As stated by bensui:
$data1 = "mathews,luks,john,ethan,neil";
$data2 = "80%,60%,78%,55%,62%";
$array = array_combine(explode(',',$data1), explode(',',$data2));
This will result in:
print_r($array);
Array
(
[mathews] => 80%
[luks] => 60%
[john] => 78%
[ethan] => 55%
[neil] => 62%
)
This will give you the ability easily update the assocaited scores simple by doing:
$array['mathews'] = '90%';
You can then use the array_slice I offered you earlier to discard john and ethan:
$newArray = array_slice($array, 2, 2);
This will give you:
print_r($newArray);
Array
(
[mathews] => 80%
[luks] => 60%
[neil] => 62%
)
Note: there is nothing wrong with using loops, the fact of the matter is they are often over used when there are methods built in to the language to solve many common problems.
If you are some kind of anti-loop fanatic, you could create a recursive function.
function no_loop_combine($data1,$data2,$index)
{
if($index == count($data1))
{
return '';
}
else
{
return $data1[$index] . ' = ' . $data2[index]
. '\n' . no_loop_combine($data1,$data2,$index + 1);
}
}
Then you just have to call your function specifying $index = 0, and you will get the result. Using array_combine probably is still using a loop, just masked by the fact that you are calling a function. Using recursion means there is no loop. Just realized that your initial input is a string, and not a loop. So you could call explode before passing it into the function as so:
no_loop_combine(explode(',', $data1 ),explode(',',$data2),0);
I have string:
ABCDEFGHIJK
And I have two arrays of positions in that string that I want to insert different things to.
Array
(
[0] => 0
[1] => 5
)
Array
(
[0] => 7
[1] => 9
)
Which if I decided to add the # character and the = character, it'd produce:
#ABCDE=FG#HI=JK
Is there any way I can do this without a complicated set of substr?
Also, # and = need to be variables that can be of any length, not just one character.
You can use string as array
$str = "ABCDEFGH";
$characters = preg_split('//', $str, -1);
And afterwards you array_splice to insert '#' or '=' to position given by array
Return the array back to string is done by:
$str = implode("",$str);
This works for any number of characters (I am using "#a" and "=b" as the character sequences):
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
$s = "ABCDEFGHIJK";
$arr = str_split($s);
$arr_add1 = array(0=>0, 1=>5);
$arr_add2 = array(0=>7, 1=>9);
$char1 = '#a';
$char2 = '=b';
$arr = array_insert($arr, $arr_add1[0], $char1);
$arr = array_insert($arr, $arr_add1[1] + strlen($char1), $char2);
$arr = array_insert($arr, $arr_add2[0]+ strlen($char1)+ strlen($char2), $char1);
$arr = array_insert($arr, $arr_add2[1]+ strlen($char1)+ strlen($char2) + strlen($char1), $char2);
$s = implode("", $arr);
print_r($s);
There is an easy function for that: substr_replace. But for this to work, you would have to structure you array differently (which would be more structured anyway), e.g.:
$replacement = array(
0 => '#',
5 => '=',
7 => '#',
9 => '='
);
Then sort the array by keys descending, using krsort:
krsort($replacement);
And then you just need to loop over the array:
$str = "ABCDEFGHIJK";
foreach($replacement as $position => $rep) {
$str = substr_replace($str, $rep, $position, 0);
}
echo $str; // prints #ABCDE=FG#HI=JK
This works by inserting the replacements starting from the end of string. And it would work with any replacement string without having to determine the length of that string.
Working DEMO