PHP output of foreach loop into a new array - php

I know I'm probably missing something easy, but I have a foreach loop and I'm trying to modify the values of the first array, and output a new array with the modifications as the new values.
Basically I'm starting with an array:
0 => A:B
1 => B:C
2 => C:D
And I'm using explode() to strip out the :'s and second letters, so I want to be left with an array:
0 => A
1 => B
2 => C
The explode() part of my function works fine, but I only seem to get single string outputs. A, B, and C.

Sounds like you want something like this?
$initial = array('A:B', 'B:C', 'C:D');
$cleaned = array();
foreach( $initial as $data ) {
$elements = explode(':', $data);
$cleaned[] = $elements[0];
}

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself
$arr = array( 0 => 'A:B', 1 => 'B:C', 2 => 'C:D');
// foreach($arr as $val) will not work.
foreach($arr as &$val) { // prefix $val with & to make it a reference to actual array values and not just copy a copy.
$temp = explode(':',$val);
$val = $temp[0];
}
var_dump($arr);
Output:
array(3) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
&string(1) "C"
}

Related

Pass by reference php

So im learning about passing by reference, what i dont understand is this, do i need to use pass by reference on functions? Like this
$items = [1,2,3,4,5];
function my_func(&$items) {
$items[] = 6;
}
my_func($items);
var_dump($items);
It will output
array(6) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) }
I have seen people adding values to array by reference like this
class play {
public function test() {
$items = [1,2,3,4,5];
foreach($items as &$item) {
$item[] = 6;
}
return $items;
}
}
$play = new play;
$play->test();
then i get Warning:
Cannot use a scalar value as an array in
Is there a way in a loop to add a value by reference outside a function?
You don't need a function to use reference variables. You can do it with ordinary assignment.
$items = [1,2,3,4,5];
$alias = &$items;
$alias[] = 6;
print_r($items);
It seems you misunderstand what the code is doing...
You have an array...
$array = [1,2,3,4,5,6];
...which can be re-written as...
$array = [
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
5 => 6,
];
// Hint: try print_r($array);
...the numbers on the left are the keys and the numbers on the right are the values.
Your loop loops through the array one row at a time:
foreach ($array as $item) {
echo $item;
}
// Output: 123456
Now, if you add the "pass by reference" operator then you can edit the value of $item; for example we could turn each item in the array to 1...
foreach ($array as &$item) {
$item = 1;
}
print_r($array);
/* Output:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
*/
Without the & in front of $item the code above would only change the value of $item inside of the foreach loop. The original array would not be touched.
The reason that you get an error is because you're assigning a value to $item as though it were an array. Where as, in fact, the $item variable is an integer. So all you need to do to make it work is remove the [] in your assignment line:
$item[] = 6;
// Becomes...
$item = 6;
If, instead of replacing a value you want to add a value then you can do that. But you need to add a value to the array which is $items NOT $item:
$items[] = 6;
Of course, doing that in a loop will add the value once for each item in the array...
I figured it out!
$result['books'][0] = ['id' => 1];
$result['books'][1] = ['id' => 2];
foreach ($result['books'] as &$book) { // use a reference
$book['new_index'] = 'new value';
$book['new_book_id'] = '29929292';
}
//unset($book); // unset the reference
echo "<pre>";
print_r($result);
echo "</pre>";

Convert a string to a multidimensional array

How can I convert the string test[1][2][3][4][5] to a multidimensional PHP array like:
array(1 => array(2 => array( 3 => array( 4 => array(5 => array()))));
If I understood your question correctly, you're asking to convert the string "test[1][2][3][4][5]" to array(1 => array(2 => array( 3 => array( 4 => array(5 => array()))));
First of all, people usually use the short array() notation, which is just [].
Second, why use strings, when you can just type
$test[1][2][3][4][5] = [];
to get what you want.
If you really want strings, you can do it in several ways, one of which is:
function makeArrayFromString($string, &$name)
{
$namePosEnd = strpos($string, '['); // name ends when first [ starts
if (!$namePosEnd) return false; // didn't find [ or doesn't start with name
$name = substr($string, 0, $namePosEnd);
$dimensionKeys = [];
$result = preg_match_all('/\[([0-9]+)\]/', $string, $dimensionKeys); // get keys
if (!$result) return false; // no matches for dimension keys
$dimensionKeys = array_reverse($dimensionKeys[1]);
$multiArray = [];
foreach ($dimensionKeys as $key)
{
$key = (int)$key; // we have string keys, turn them to integers
$temp = [];
$temp[$key] = $multiArray;
$multiArray = $temp;
}
return $multiArray;
}
$string = 'test[1][2][3][4][5]';
$name = '';
$multiArray = makeArrayFromString($string, $name);
if ($multiArray === false)
exit('Error creating the multidimensional array from string.');
$$name = $multiArray; // assign the array to the variable name stored in $name
var_dump($test); // let's check if it worked!
Outputs:
array(1) {
[1]=>
array(1) {
[2]=>
array(1) {
[3]=>
array(1) {
[4]=>
array(1) {
[5]=>
array(0) {
}
}
}
}
}
}
Keep in mind that I didn't add any checks if the $name string satisfies the PHP variable naming rules. So you might get an error if you do something like 111onetest[1][2][3][4][5], as variable names in PHP can't start with a number.

PHP: Parse and split key and value in array

I have this kind of array
array(1) {
["key,language,text"] => "home,es,casa"
}
Is it possible to parse it and split it to have
array(3) {
['key'] => "home" ,
['language'] => "es" ,
['text'] => "casa"
}
My actual solution is to do the following but I'm pretty sure that I can find a better approach
$test = explode(',', $my_array['key,language,text']);
$my_array['key'] = $test[0];
$my_array['language'] = $test[1];
$my_array['text'] = $test[2];
You can use array_combine to create an array from an array of keys and values, providing the length of each is equal, it will return false if there is a mismatch.
foreach($array as $keys_str => $values_str) {
$keys = explode(",", $keys_str);
$values = explode(",", $values_str);
$kv_array = array_combine($keys, $values);
}
$kv_array would be in the format you're after.
Give it a try..
$arr = array("key,language,text" => "home,es,casa");
$val = explode(",", $arr[key($arr)]);
foreach(explode(",", key($arr)) as $k => $key){
$data[$key] = $val[$k];
}
If you have an array with only 1 entry:
$a = ["key,language,text" => "home,es,casa"];
you could use reset which will return the value of the first array element and key which will return the key of the array element that's currently being pointed to by the internal pointer.
Then use explode and use a comma as the delimiter and use array_combine using the arrays from explode for the keys and the values to create the result.
$result = array_combine(explode(',', key($a)), explode(',', reset($a)));
print_r($result);
That will give you:
array(3) {
["key"]=>
string(4) "home"
["language"]=>
string(2) "es"
["text"]=>
string(4) "casa"
}
This best solution for you :
//this your problem
$array = [
"key,language,text" => "home,es,casa",
"key,language,text" => "home1,es1,casa1"
];
$colms_tmp = 0;
//this your solution, foreach all
foreach($array as $key => $val){
//split your value
$values = explode(",",$val);
//foreach the key (WITH COLMNS), $colm is number of key after explode
foreach(explode(",",$key) as $colm => $the_key){
$result[$colms_tmp][$the_key] = $values[$colm];
}
$colms_tmp++;
}
i haven't try it, but i think this can help you.

How to Seperate Array with equals to and create single array

Hi I am working on very complex array operations.
I have $temp variable which stores pipe separated string like Height=10|Width=20
I have used explode function to convert into array and get specific output.
Below code i have try :
$product_attributes = explode("|",$temp)
//below output i get after the explode.
$product_attributes
Array(
[0]=>Height=10
[1]=>width=20
)
But i want to parse this array to separate one.
My expected output :
Array (
[0]=>Array(
[0] => Height
[1] => 10
)
[1]=>Array(
[0]=>Width
[1]=>20
)
)
Which function i need to used to get the desire output ?
Before downvoting let me know if i have made any mistake
You could try the below code. I've tested this and it outputs the result you've shown in your post.
$temp = 'Height=10|Width=20';
$product_attributes = explode('|', $temp);
$product_attributes2 = array();
foreach ($product_attributes as $attribute) {
$product_attributes2[] = explode('=', $attribute);
}
print_r($product_attributes2);
Try Below code
<?php
$temp = "Height=10|Width=20";
$product_attributes = explode("|", $temp);
foreach ($product_attributes as $k => $v) {
$product_attributes[$k] = explode('=', $v);
}
echo '<pre>';
print_r($product_attributes);
?>
check running answer here
Process your result by this:
$f = function($value) { return explode('=', $value); }
$result = array_map($f, $product_attributes);
One more option is to split the values in to one array and then build them from there.
$str = "Height=10|Width=20";
$arr = preg_split("/\||=/", $str);
$arr2= array();
$j=0;
for($i=0;$i<count($arr);$i++){
$arr2[$j][]= $arr[$i];
$arr2[$j][]= $arr[$i+1];
$i++;
$j++;
}
var_dump($arr2);
The output will be:
$arr = array(4){
0 => Height
1 => 10
2 => Width
3 => 20
}
$arr2 = array(2) {
[0]=>
array(2) {
[0]=>
string(6) "Height"
[1]=>
string(2) "10"
}
[1]=>
array(2) {
[0]=>
string(5) "Width"
[1]=>
string(2) "20"
}
}

Sort then split a PHP array?

Here is a var_dump of my array:
array(6) {
[0]=> string(4) "quack"
["DOG"]=> string(4) "quack"
[1]=> string(4) "quack"
["CAT"]=> string(4) "quack"
[2]=> string(4) "Aaaaarrrrrggggghhhhh"
["CAERBANNOG"]=> string(4) "Aaaaarrrrrggggghhhhh"
}
(just for fun I've included two puns in this code, try and find them!)
How do I split this array into two arrays, one containing all the quacks; the other Aaaaarrrrrggggghhhhh?
Note that it won't always be in consecutive order, so was thinking maybe nested hashmaps, something like:
Check if (isset($myarr['$found_val']))
Append that array if found
Else create that place with a new array
But not sure how the arrays are implemented, so could be O(n) to append, in which case I'd need some other solution...
You can just group them based on values and store the keys
$array = array(0 => "quack","DOG" => "quack",1 => "quack","CAT" => "quack",2 => "Aaaaarrrrrggggghhhhh","CAERBANNOG" => "Aaaaarrrrrggggghhhhh");
$final = array();
foreach ( $array as $key => $value ) {
if (! array_key_exists($value, $final)) {
$final[$value] = array();
}
$final[$value][] = $key;
}
var_dump($final);
Output
array
'quack' =>
array
0 => int 0
1 => string 'DOG' (length=3)
2 => int 1
3 => string 'CAT' (length=3)
'Aaaaarrrrrggggghhhhh' =>
array
0 => int 2
1 => string 'CAERBANNOG' (length=10)
Try this
$quacks_arr = array_intersect($your_array, array('quack'));
$argh_arr = array_intersect($your_array, array('Aaaaarrrrrggggghhhhh'));
If you want to sort them, then just do ksort
ksort($quacks_arr);
ksort($argh_arr);
Just in case anyone wants to do this in a more of and odd way:
Updated with air4x's idea of using only a single item array, instead of array_fill(0,count($a),$v). Makes it's much more sensible.
$a = array(
0 => "quack",
"DOG" => "quack",
1 => "quack",
"CAT" => "quack",
2 => "Aaaaarrrrrggggghhhhh",
"CAERBANNOG" => "Aaaaarrrrrggggghhhhh"
);
$b = array();
foreach( array_unique(array_values($a)) as $v ) {
$b[$v] = array_intersect($a, array($v));
}
echo '<xmp>';
print_r($b);
Totally not optimal - difficult to read - but still interesting :)

Categories