Is there a way to set the value of members of an array with foreach?
<?
$arr = array(0=>'a',1=>'b',2=>'c',3=>'d');
foreach($arr as $key => $value){
$value = 'a';
}
var_dump($arr);
?>
returns:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
}
Where what I am trying to get it to return is:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "a"
[2]=>
string(1) "a"
[3]=>
string(1) "a"
}
Here is a link to the codepad I was using.
http://codepad.org/FQpPYFtz
$arr = array(0=>'a',1=>'b',2=>'c',3=>'d');
foreach($arr as $key => &$value) { // <-- use reference to $value
$value = 'a';
}
var_dump($arr);
It is quite simple:
foreach ($data as $key => $value) {
$data[$key] = 'new value';
}
Related
Output of var_dump($arr)
array(4) {
[0]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(2) "4
"
}
[1]=>
array(4) {
[0]=>
string(1) "5"
[1]=>
string(1) "6"
[2]=>
string(1) "7"
[3]=>
string(2) "8
"
}
[2]=>
array(4) {
[0]=>
string(1) "9"
[1]=>
string(2) "10"
[2]=>
string(2) "11"
[3]=>
string(3) "12
"
}
[3]=>
array(4) {
[0]=>
string(2) "13"
[1]=>
string(2) "14"
[2]=>
string(2) "15"
[3]=>
string(2) "16"
}
}
i Want to remove \n in $arr array.
I tried to use array_walk($arr,'intval'); but it did not work, because it is multiple dimensional array. What's the solution?
Is there any inbuilt PHP function? Or I need to use loops and remove it?
P.S: I am a newbie, try not to get too technical.
You can just do
array_walk_recursive($arr, function(&$v) { $v = trim($v); });
You cannot use trim directly as the callback, because it doesn't accept arguments by reference, so you have to wrap it in a callback that does.
Demo https://eval.in/904410
You can achieve this via loop and array_map()
$arr = array(
array("1", "2", "3", "4\n"),
array("5", "6", "7", "8\n"),
array("9", "10", "11", "12\n"),
array("13", "14", "15", "16\n"),
);
// result array
$result = [];
// Loop thru array
foreach ($arr as $value) {
// Map thru $value with trim to remove \n then push to result
$result[] = array_map('trim', $value);
}
// Output
echo('<pre>');
print_r($result);
There are alternatives, but recursively looping through your array gives you flexibility about what to remove, not only newlines:
function removeNewline($array) {
$result = array();
foreach ($array as $key => $value) {
// If the array value is an array itself, call the function recursively
if (is_array($value)) {
$result[$key] = removeNewline($value);
} else {
// Only remove newlines from strings
if (is_string($value)) {
$result[$key] = preg_replace('/\s+/', '', $value);
} else {
$result[$key] = $value;
}
}
return $result;
}
I have a PHP array, which looks like follows:
array(8) {
[0]=>
string(3) "639"
[1]=>
string(2) "33"
[2]=>
string(2) "68"
[3]=>
string(3) "196"
[4]=>
string(3) "275"
[5]=>
string(3) "309"
[6]=>
string(3) "331"
[7]=>
string(3) "378"
}
I would like to change all the keys to these values to incrementing letters (a, b, c, etc.) - how would I do this?
I realise I can increment letters like so:
$x = "a";
$x++;
echo $x;
"b"
But how can I perform this within a loop?
The desired result would be something like this:
"a" => "639"
"b" => "33"
"c" => "68"
etc.
I think the following can help
$newArray = array();
$index = "a";
foreach($oldArray as $value)
{
$newArray[$index] = $value;
$index++;
}
You have provided the answer pretty much yourself already
$array = array('639', '33', '68', '196', '275', '309', '331', '378');
$index = 'a';
$newArray = array();
foreach ($array as $value) {
$newArray[$index++] = $value;
}
Following code will surely help you:
$result = [];
array_walk($data,function($v,$k)use (&$result){
$result[chr(65 + $k)] = $v;
});
print_r($result);
Demo
Played for hours, but couldn't do this. Task looks very simple, though..I need recursively combine 2 arrays into one. Using first array's values as keys, and second array's leave values as they are. This is what I have:
array(2) {
[0]=>
array(4) {
[0]=>
string(9) "First"
[1]=>
string(6) "Something"
}
[1]=>
array(4) {
[0]=>
string(3) "More"
[1]=>
string(6) "Nomore"
}
}
Second array
array(2) {
[0]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
[1]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
}
What I'm trying to achive:
array(2) {
[0]=>
array(4) {
["First"]=>
string(1) "1"
["Something"]=>
string(1) "2"
}
[1]=>
array(4) {
["More"]=>
string(1) "1"
["Nomore"]=>
string(1) "2"
}
}
Another solution using array_combine
$first_array = array(
array('first', 'second', 'third'),
array('more1', 'more2', 'more3'),
);
$second_array = array(
array('val1', 'val2', 'val3'),
array('2val1', '2val2', '2val3')
);
$new_array = array();
foreach($first_array AS $k => $v) {
$new_array[$k] = array_combine($v,$second_array[$k]);
}
$firstArray = array(
array('first', 'second', 'third'),
array('more1', 'more2', 'more3'),
);
$secondArray = array(
array('val1', 'val2', 'val3'),
array('2val1', '2val2', '2val3')
);
$newArray = array();
for ($i=0; $i<count($firstArray); ++$i) {
$subArray1 = $firstArray[$i];
$subArray2 = $secondArray[$i];
$newArray[$i] = array();
for ($j=0; $j<count($subArray1); ++$j) {
$key = $subArray1[$j];
$value = $subArray2[$j];
$newArray[$i][$key] = $value;
}
}
var_dump($newArray);
Wouldn't be more elegant to do something like this ?
$newArray = array();
foreach ($firstArray as $key => $firstVal)
foreach ($secondArray as $key => $secondVal)
array_push($newArray, array_combine($firstVal, $secondVal));
This way you'll have the same result you wanted inside $newArray
with a bit simpler code.
I haven't tested that though, let me know if it works or breaks :)
Here is an example...
I have the following code:
$a=array("a","b","c");
$b=array("1","2","3");
$c = array_merge($a,$b);
echo "<pre>";
var_dump($c);
echo "</pre>";
Gives me an output:
array(6) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "1"
[4]=>
string(1) "2"
[5]=>
string(1) "3"
}
How could I change the code so that it gives me this output instead:
array(3) {
[0]=>
string(5) "a','1"
[1]=>
string(5) "b','2"
[2]=>
string(5) "c','3"
Any ideas?
$c = array_map(function ($a, $b) { return "$a','$b"; }, $a, $b);
For whatever that's good for...
Using SPL's MultipleIterator:
$a = array("a","b","c");
$b = array("1","2","3");
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$c = array();
foreach($mi as $row) {
$c[] = $row[0] . "','" . $row[1];
}
var_dump($c);
If the keys to both arrays are always in parity, you could do something like
foreach ($a as $key => $value) {
$newArray[] = "$value','{$b[$key]}";
}
var_dump($newArray);
// would output the below
array(3) {
[0]=>
string(5) "a','1"
[1]=>
string(5) "b','2"
[2]=>
string(5) "c','3"
However, the result looks a little weird, are you sure this is what you are trying to achieve?
$a=array("a","b","c");
$b=array("1","2","3");
if(count($a) > count($b)){
foreach($a as $key => $value)
$c[$key] = isset($b[$key])? $value.",".$b[$key] : $value;
} else {
foreach($b as $key => $value)
$c[$key] = isset($a[$key])? $a[$key].",".$value : $value;
}
Use above code it will for your array.
I have a session that looks like this:
array(3) {
["counter"]=>
int(0)
["currentItem"]=>
string(1) "2"
["addedToCart"]=>
array(12) {
[0]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(2) "21"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
[1]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(1) "7"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
[2]=>
array(11) {
["aantal"]=>
int(1)
["id"]=>
string(1) "1"
["filmtitel"]=>
string(11) "a_bugs_life"
["film_id"]=>
string(1) "2"
["zaal_id"]=>
string(1) "1"
["zaaltitel"]=>
string(6) "zaal 1"
["tijdstip"]=>
string(8) "15:00:00"
["stoeltjes"]=>
string(2) "22"
["dag"]=>
string(8) "woensdag"
["verwijder"]=>
int(2)
["vertoningId"]=>
string(1) "3"
}
}
}
Now, from $_SESSION['addedToCart] I would like to remove arrays if they meet to certain conditions. I have tried the following.
foreach ($_SESSION["addedToCart"] as $arr) {
if ($arr["stoeltjes"] == $stoeltje && $arr['film_id'] == $id) {
unset($arr);
}
}
This doesn't seem to work, it doesn't remove anything, I did a var_dump to check if the variables $stoeltje and $id were fine and they were fine so that cant be the problem.
Am I able to use unset in this kind of situation?
foreach ($_SESSION["addedToCart"] as &$arr)
& turns your variable into a reference instead of a copy. Normally this would be sufficient. unset() only works on data within the current scope (so your foreach loop) leaving the original unchanged (See unset() for details).
Instead you can do:
foreach ($_SESSION["addedToCart"] as $key => $val)
{
if ($val["stoeltjes"] == $stoeltje && $val['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
Even if the suggested way with the reference should work normally, here's an example without it:
foreach ($_SESSION["addedToCart"] as $key => $arr) {
if ($arr["stoeltjes"] == $stoeltje && $arr['film_id'] == $id) {
unset($_SESSION["addedToCart"][$key]);
}
}
It doesn't work, because foreach is working on a copy, therefore $arr is just a copy of each element in the main table.
from php.net:
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
Try this:
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => &$value) {
if ($value == 2)
{
unset($arr[$key]);
}
}
print_r($arr);
remove_array_key("film_id", $array);
function remove_array_key($key, &$array)
{
$result = array_key_exists($key, $array);
if ($result) {
unset($array[$key]);
return $array;
}
foreach ($array as &$v) {
if (is_array($v)) {
$result = remove_array_key($key, $v);
}
if (is_array($result)) {
unset($v[$key]);
return $array;
}
}
return false;
}
Link to Github Explanation