Array's key and value into a string - php

I'm currently new to coding and I'm trying to complete an exercise I have. I've tried to figure this out on my own, for hours now and for the life of me I can't seem to get it right... Here is the question:
''Create an array with the keys: "one", "two", "three", "four" and
"five" and the values: 1, 2, 3, 4, 5. Use a foreach-loop to add all keys and values to an array in the format: ["key"=value, "key"=value, etc]. Use implode() to make the answer a string with all items separated by a
comma ,.''
The code I have written is as follows:
$words = ["one", "two", "three", "four", "five"];
$numbas = [1, 2, 3, 4, 5];
$combined = array_combine($words, $numbas);
foreach ($combined as $key => $value) {
$forimplode = "$key = $value";
}
$imploded = implode(",", $forimplode);
$ANSWER = $imploded;
To me, this looks perfectly fine, but Yeah, I don't know what is going wrong. I really don't.. Haha.. I appreciate all help I'll be given and I'll sure to learn from my mistakes.

To me, this looks perfectly fine
And to me - not. Because every iteration of foreach overwrites $forimplode with a new string value. Instead, $forimplode should be declared as array and on each iteration new string should be add as a new item to $forimplode:
$forimplode = array();
foreach ($combined as $key => $value) {
$forimplode[] = "$key = $value";
}
$imploded = implode(",", $forimplode);

You are redeclaring your array every single time the for loop runs. Try this:
$forimplode = array();
foreach ($combined as $key => $value) {
$forimplode[] = "$key = $value";
}

Related

Key of associative table

I have a little problem in my project : I would like display only the key of each array when I click on a element of my list. Dump of my table
For example when I click in "Paupiette", I would like display 0.
I partially succeeded but when I click in a element, I see only the last key (here "1").
Here,you can see the code
$carts = $cartService->getCart($user);
//dump($carts); die;
$mykey = 0;
foreach($carts as $key => $value) {
$mykey = $key;
}
dump($mykey);die;
If you have any idea, thank you a lot
You have multiple choice to display your $keys
the first one is :
$keys = array_keys($carts);
The second is :
foreach ($carts as $key => $value) {
dump($key);
}
if you will display all keys after loop
$myKeys = array();
foreach($carts as $key => $value) {
$myKeys[] = $key;
}
dump($myKeys);die;
If you just want to display the keys, following your coding "style":
foreach ($carts as $key => $value) {
dump($key);
}
If you want to display the keys as comma-separated string, again following your coding "style":
$keys = array_keys($carts); // Get the keys, eg, [0, 1];
$str = implode(', ', $keys); // Convert the array to string, eg, "0, 1"
dump($str);

Retrieve Highest Value from Array in PHP

I would post the entire code, but it is lengthly and confusing, so I'll keep it short and simple. This is complicated for myself, so any help will be greatly appreciated!
These are the values from my Array:
Light Blue1
Blue2
Blue1
Black3
Black2
Black1
The values I need to retrieve from my Array are "Light Blue1", "Blue2" and "Black3". These are the "highest values" for each color.
Something similar to what I'm looking for is array_unique, but that wouldn't work here. So something along those lines that can retrieve each color with its highest number.
Thanks!
Assuming your format is always NameNumber a regex should do the trick for separating the data. This will loop through your data in the order your provide and grab the first element that is different and put it into $vals. I am also assuming your data will always be ordered as your example shows
$data = ['Light Blue1',
'Blue2',
'Blue1',
'Black3',
'Black2',
'Black1'];
$vals = [];
$current = '';
foreach($data as $row) {
if(!preg_match('/(.*)(\d)/i', $row, $matched)) continue;
if($matched[1] != $current) {
$vals[] = $row;
$current = $matched[1];
}
}
The solution using preg_split and max functions:
$colors = ['Light Blue1', 'Blue2', 'Blue1', 'Black3', 'Black2', 'Black1'];
$unique_colors = $result = [];
foreach ($colors as $k => $v) {
$parts = preg_split("/(\d+)/", $v, 0, PREG_SPLIT_DELIM_CAPTURE);
$unique_colors[$parts[0]][] = (int) $parts[1];
}
foreach ($unique_colors as $k => $v) {
$result[] = $k . max($v);
}
print_r($result);
The output:
Array
(
[0] => Light Blue1
[1] => Blue2
[2] => Black3
)
If you pre-sort your array with "natural sorting", then you can loop through the array and unconditionally push values into the result with digitally-trimmed keys. This will effectively overwrite color entries with lesser number values and only store the the highest numbered color when the loop finishes.
Code: (Demo)
natsort($data);
$result = [];
foreach ($data as $value) {
$result[rtrim($value, '0..9')] = $value;
}
var_export(array_values($result));
Or you could parse each string and compare the number against its cached number (if encountered before): (Demo)
$result = [];
foreach ($data as $value) {
sscanf($value, '%[^0-9]%d', $color, $number);
if (!isset($result[$color]) || $result[$color]['number'] < $number) {
$result[$color] = ['value' => $value, 'number' => $number];
}
}
var_export(array_column($result, 'value'));
A related technique to find the highest value in a group

in php how do i make an like array("one","two","three") into $somearray["one"]["two"]["three"]?

I would like to take an array, say:
array("one", "two", "three");
and make it into an array of arrays, like:
$someArray["one"]["two"]["three"];
The array of arrays ($someArray) would have to be created by some sort of loop as the initial array is created by an explode() so i don't know how deep $someArray would be.
I hope this is clear, thanks all for your time!
I am reading up on it at the moment myself, would array_map() work for this?
You can do this:
$path = array("one", "two", "three");
$ref = &$arr;
foreach ($path as $key) {
if (!isset($ref[$key])) break;
$ref = &$ref[$key];
}
At the end $ref is a reference to $arr['one']['two']['three'] if it exists. And if you replace break by $ref[$key] = array() you will build an array with that structure instead.
You should use array_reduce.
The solution is quite simple.
To do the trick, reverse the array and only then apply the reduction.
$a = array('a','b','c');
$x = array_reduce(array_reverse($a), function ($r, $c) {
return array($c=>$r);
},array());
EDIT an expanded and explained version:
In php we don't have a function to go deep into an array automatically but we haven't to.
If you start from the bottom, we will be able to enclose an array into the previous one
with a simple assignation.
$a = array('a','b','c');
$result=array(); // initially the accumulator is empty
$result = array_reduce(
array_reverse($a),
function ($partialResult, $currentElement) {
/* enclose the partially computed result into a key of a new array */
$partialResult = array($currentElement=>$partialResult);
return $partialResult;
},
$result
);
By the way I prefer the shorter form. I think it is a functional idiom and doesn't need further explanation to a middle experienced developer (with a bit of functional background). The second one add a lot of noise that, it is suitable to learn but source
of distraction into production code (obviously I'm referring to function with just a return statement).
i'm not sure why you would want this.
But but the basis of what your wanting would be like this
$numbers = array("one", "two", "three");
$array = array();
$pointer = &$array;
$last_val = NULL;
foreach($numbers as $key => $val){
if(!empty($pointer[$last_val])){
$pointer = &$pointer[$last_val];
$pointer = new array($val);
$last_val = $val;
}else{
$pointer = new array($val);
$last_val = $val;
}
}
This should then right what you want to $array;
This is untested but i think that should work if it does not just tell me what its doing and i will have a look
$arrNew = array();
$ref = &$arrNew;
$arrParts = array("one", "two", "three");
foreach($arrParts as $arrPart){
$ref[$arrPart] = array();
$ref = &$ref[$arrPart];
}
When you print $arrNew, It will print this..
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
)
)
)
)

Understanding Arrays as part of the foreach in php

Having:
$a as $key => $value;
is the same as having:
$a=array();
?
No, it's not. It's more like
list($key, $value) = each($arr);
See the manual
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
is identical to
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
Also see
The while Control Structure
list — Assign variables as if they were an array
each — Return the current key and value pair from an array and advance the array cursor
reset — Set the internal pointer of an array to its first element
First of all it has to say
foreach($a as $key => $value)
Then, as far as I know,
foreach($a = array())
doesn't compile.
That said, if you foreach, you iterate through the elements of an array. With the 'as' keyword, you get pairs of key/value for each element, where $key would be the index by which you can get $value:
$value = $a[$key];
Did this answer your question? If not, please specify.
edit:
In other programming languages it would spell something like
foreach($key => $value in $a)
or (C#)
foreach(KeyValuePair<type1, type2> kv in a)
which I think is more intuitive, but basically the same.
if you have the following:
$a = array('foo' => array('element1', 'element2'), 'bar' => array('sub1', 'sub2'));
if you use $a as $key=> $value in the foreach loop,
$key will be 'foo', and $value will be array('element1', 'element2') in the first iteration, in the second $key == 'bar' and $value == array('sub1', 'sub2').
If you loop over an array using foreach, the array is the first expression inside the parenthesis.
It can be a variable, like $a, or an array literal like array(1, 2, 3). The following loops are identical:
With an array literal:
foreach(array(1, 2, 3) as $number)
print($number);
With a variable:
$a = array(1, 2, 3);
foreach($a as $number)
print($number);

Exploding Arrays in PHP While Keeping the Original Key

How can I do the following without lots of complicated code?
Explode each value of an array in PHP (I sort of know how to do this step)
Discard the first part
Keep the original key for the second part (I know there will be only two parts)
By this, I mean the following:
$array[1]=blue,green
$array[2]=yellow,red
becomes
$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow
I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.
given this:
$array[1] = "blue,green";
$array[2] = "yellow,red";
Here's how to do it:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
Another way you could do it would be like this:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
... or use a combination of substr() and strpos()
Try this:
$arr = explode(',','a,b,c');
unset($arr[0]);
Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:
list(,$what_i_want) = explode('|','A|B',2);
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
The array you start with:
$array[1] = "blue,green";
$array[2] = "yellow,red";
One way of coding it:
function reduction($values)
{
// Assumes the last part is what you want (regardless of how many you have.)
return array_pop(explode(",", $values));
}
$prime = array_map('reduction', $array);
Note: This creates a different array than $array.
Therefore $array == $prime but is not $array === $prime

Categories