I want to merge 2 arrays by concatenating their values. Right now I use array_merge(), but that doesn't give me the expected result.
Code:
$software1 = $_POST['software1'];
$software2 = $_POST['software2'];
$software3 = array_filter($software2);
$result = array_merge($software1, $software3);
foreach($result as $value){
echo $value . "<br>";
}
Current output:
software
software
software
1
2
3
What I would like:
software 1
software 2
software 3
Just another way to do it: if $software2 are unique value, you can use array_combine:
foreach (array_combine($_POST['software2'], $_POST['software1']) as $key => $val) {
echo $val , ' ', $key;
}
You want to use array_map() here and concatenate both corresponding values from both arrays together creating a new array, e.g.
$result = array_map(function(...$v){
return implode(" ", $v);
}, $software1, $software3 /* , more arrays */);
Of course if you just want to output it you can use echo inside array_map(). And if you have an unknown amount of arrays you want to merge by concatenation you can do it with call_user_func_array(), e.g.
$result = call_user_func_array("array_map", [function(...$v){return implode(" ", $v);}, $arrays]);
Several ways. Here are two:
foreach($software1 as $key => $value){
echo "$value {$software2[$key]}<br>";
}
Or if one or the other are guaranteed to be unique, use it as the key:
foreach(array_combine($software1, $software2) as $key => $value){
echo "$key $value<br>";
}
Related
since I've tried different things - like for/while-loops, I finally ended up here. What I'm trying to do is to merge different x arrays (from a form) into one array, so that I can count the answers. My code for merging actually looks like this:
foreach($_POST as $key =>$value){
foreach ($value as $answer){
echo $answer."<br />";
}
$tmp+=1;
$data[$key] = $value;
}
$results = array_merge($data['q1'], $data['q2']);
I'd like to input the content of array_merge based on how many questions (q1, q2, ...) are in the form. So I tried this:
$array_loop = array();
for ($k = 1 ; $k < $tmp; $k++) {
$array_loop.='$data["q' . $k . '"], ';
};
Of course, it's not working because it's an array so string conversion. Any hints?
you can use
$result = array_merge(...$array_loop);
to save multiple arrays into one array
I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array
I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()
I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);
Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");