Merge Arrays But Join Corresponding Keys [duplicate] - php

This question already has answers here:
Transpose multidimensional array and join values with commas [duplicate]
(2 answers)
Closed 10 months ago.
I am trying to achieve the following functionality:
There is 5 textareas, the user inputs several words on different lines into the textarea, on click of a button it creates arrays from these textareas and the merges the array whilst appending the corresponding keys.
Textarea 1:
example 1
example 1 other
Textarea 2:
example 2
example 2 other
Using:
$col1 = $_POST['txta1']; $col1Array = explode("\n", str_replace("\r", "", $col1));
$col2 = $_POST['txta2']; $col2Array = explode("\n", str_replace("\r", "", $col2));
This will now give me an array for each keyword, separating the textarea value based on a new line.
I now want to combine the 2 arrays so that key [0] appends the first array and so on, it should become
array([0]=>'example 1 example 2',[1]=>'example 1 other example 2 other');
In order for me to the echo out into another textarea, the results whilst should be:
example 1 example 2
example 1 other example 2 other

You can pass both the arrays to array_map to pivot them into the format you want, then implode the inner arrays so you end up with an array of strings rather than an array of arrays.
$result = array_map(
function(...$row) { return implode(' ', $row); },
$col1Array, $col2Array
);

Related

Filter array by skipping every 2nd and 3rd element from array [duplicate]

This question already has answers here:
Selecting every nth item from an array
(9 answers)
Remove every 3rd and 4th element from array in php
(1 answer)
How to access N-th element of an array in PHP
(3 answers)
Remove every nth item from array
(6 answers)
foreach step 5 steps forward in an array
(3 answers)
Closed 4 months ago.
i have a array like this
$names = [a,b,c,d,e,f,g,h,i,j,k,l,m];
what i wan to remove
$remove = "b,c,e,f,h,i,k,l";
then i need a new array from the remaining elements like below
$new_arr = [a,d,g,j,m];
Use array chunk to split by 3 and take out first element.
<?php
$names = [a,b,c,d,e,f,g,h,i,j,k,l,m];
$chunked =array_chunk($names, 3);
$filtered = [];
foreach($chunked as $chunk){
$filtered[] = $chunk[0];
}
var_dump($filtered);
?>
Instead of removing number 2 and number 3 from each 3 elements, the task is simply written like this:
Keep the first of every 3 items.
This can be determined using the index and the modulo operator %.
Using array_filter saves the foreach loop. This allows the solution to be implemented as a one-liner.
$names = ['a','b','c','d','e','f','g','h','i','j','k','l','m'];
$result = array_filter($names,fn($k) => $k%3 == 0, ARRAY_FILTER_USE_KEY );
var_dump($result);
Demo: https://3v4l.org/sKTSQ
The $names array needs to be noted as in the code above. A notation without quotes like in the question produces error messages.

How to exact match both keys and values in both arrays in php [duplicate]

This question already has answers here:
PHP - Check if two arrays are equal
(19 answers)
Closed 5 years ago.
I have two arrays i want to match exact both keys and values of arrays one of array be three dimensional or more
Example
$arr1 = ['status'=>true,'message'=>'data saved'];
$arr2 = ['status'=>true,'message'=>'data saved'];
in this scenario array return 1 but they are not equal
$arr1 = array("messagess"=>"data added","status" => true);
$arr2 = array("status" => true,'message'=>'data has been added');
echo count(array_intersect_assoc($arr1,$arr2));
Expected should be true if both exact match otherwise false. I have tried array_intersect() and other methods but failed.
Please Guide!
Thank in Advance
You could use array_intersect_assoc() and count the resulting number
echo count(array_intersect_assoc($arr1,$arr2));
http://php.net/manual/en/function.array-intersect-assoc.php
If the number in count is the same of the number of index keys you want check the the two array are the same otherwise you get the number of key values that match

loop through a multi-dimensional array and echo the value in PHP [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have a multi-dimensional array that takes the form:
array = [value1, some number],[value2, some number]...
I need to loop through the array and echo the value followed by a tokenizer so the final output looks like:
value1!##$value2!##$
I know that I have to concatenate the return value with ."!##$" but I do not know how to loop through the array. Can anyone offer some help.
My array is being made from a MySQL Query as follows:
while($row = $results -> fetch_assoc()) {
$return_array[] = array(
$row['uid'],($row['column1] - $row['column2']));
}
Then I am perfoming a usort on the array
To be simple enough, you can use implode and array_column:
$array = [['value1', 123], ['value2', 234]];
echo implode('!##$', array_column($array, 0)) . '!##$';
This gives:
value1!##$value2!##$
Explanation:
implode - Joins array values using some specified value, here !##$
array_column - implode accepts one dimensional array, also you want only the first index of the array to be joined, so creating an array with just first index.

Easy way to parse array values [duplicate]

This question already has answers here:
Applying a function for each value of an array
(5 answers)
Closed 6 years ago.
Is there util that parses array content without the need of iterating it and parsing each value?
input: ['2','3','7']
output: [2, 3, 7]
This obviously iterates internally, but you don't have to code an iterator:
$output = array_map('intval', $input);
Maps every value in $input to the intval() function and returns the result. For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.
I can't tell if you want to remove 0 values or not from your comment, but if so:
$output = array_filter(array_map('intval', $input));
You can use array_map
array = ["2","3","4"];
$intArray = array_map('intval', $array);

Count and read multiple input in one text field [duplicate]

This question already has answers here:
php count the number of strings after exploded
(5 answers)
Closed 8 years ago.
I need to create a text field that can get multiple input like this...
1, 2, 3, 4
Then the output should be...
Number of input: 4
Mean: 2.5
The problem is how can I count the number of the input, I mean how the program know that how many input that user type into the text field, and use each value to calculate a summation for all. Does anybody has any methods or any idea?
Thanks.
Use explode(); and explode all the commas (,). That will give you an array.
From there, use count and a loop for counting and get the mean. Use trim() aswel for getting rid of empty spaces.
You can test the code here: http://writecodeonline.com/php/
$input = "1, 2, 3, 4";
//remove all whitespace
$input = str_replace(' ', '', $input);
//turn the string into an array of integers
$numbers= array_map('intval', explode(',', $input));
//the number of elements
$count = count( $numbers );
//sum the numbers
$sum = array_sum( $numbers );
//print the number of inputs, a new line character, and the mean
echo "Number of inputs: $count\r\n";
echo 'Mean: ' . $sum / $count;

Categories