Create groups of values from array values [duplicate] - php

This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing

You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}

You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)

Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.

Related

How to keep only empty elements in array in php?

I have one array and i want to keep only blank values in array in php so how can i achieve that ?
My array is like
$array = array(0=>5,1=>6,2=>7,3=>'',4=>'');
so in result array
$array = array(3=>'',4=>'');
I want like this with existing keys.
You can use array_filter.
function isBlank($arrayValue): bool
{
return '' === $arrayValue;
}
$array = array(0 => 5, 1 => 6, 2 => 7, 3 => '', 4 => '');
var_dump(array_filter($array, 'isBlank'));
use for each loop like this
foreach($array as $x=>$value)
if($value=="")
{
$save=array($x=>$value)
}
if you want print then use print_r in loop
there is likely a fancy built in function but I would:
foreach($arry as $k=>$v){
if($v != ''){
unset($arry[$k]);
}
}
the problem is; you are not using an associative array so I am pretty sure the resulting values would be (from your example) $array = array(0=>'',1=>''); so you would need to:
$newArry = array();
foreach($arry as $k=>$v){
if($v == ''){
$newArry[$k] = $v;
}
}

How to remove only item of array? [duplicate]

This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 5 years ago.
I have an array.
$a_input = array(1,2,3,4,5)
I want to remove 1 from array . out put is :
array(2,3,4,5);
remove 2 => output:
array(1,3,4,5);
remove 3 => output :
array(1,2,4,5);
.....
how to do this with for loop ?
try this
$a_input = array(1,2,3,4,5);
$cnt=count($a_input);
for($i=0;$i<$cnt;$i++){
$remove = array($i+1);
$output1=array_diff($a_input,$remove);
var_dump("<pre>",$output1);
}
Online test
use unset.
foreach($a_input as $key => $val){
if($a_input[$key]==1) unset($a_input[$key]);
}
You can use
$array = array(1,2,3,4,5);
if (($key = array_search('1', $array)) !== false) {
unset($array[$key]);
}
Here we are searching a value in the array If it is present, then proceed to get the key at which required value is present, then unseting that value.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$a_input = array(1,2,3,4,5);
$numberToSearch=2;
if(in_array($numberToSearch,$a_input))//checking whether value is present in array or not.
{
$key=array_search($numberToSearch, $a_input);//getting the value of key.
unset($a_input[$key]);//unsetting the value
}
print_r($a_input);
Output:
Array
(
[0] => 1
[2] => 3
[3] => 4
[4] => 5
)
What you need is array_filter:
$input = array(1,2,3,4,5)
$remove = 1;
$result = array_filter($input, function ($val) use ($remove) {
return $val !== $remove;
});
You need array_diff.
$a_input = array(1,2,3,4,5);
you can create new array with values like below:
$remove = array(1,2);
$result=array_diff($a_input,$remove);
output:
array(3,4,5);
Most of the programmer use this way only.And this will work for multiple elements also.

Explode a string into bidimensional array

Excuse me if this question was already solved. I've searched trough the site and couldn't find an answer.
I'm trying to build a bi-dimensional array from a string. The string has this structure:
$workers="name1:age1/name2:age2/name3:age3"
The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".
I know the basics about the explode function:
$array=explode("separator","$string");
But I have no idea how to face this to make it bidimensional. Any help would be appreciated.
Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.
$row = 0;
foreach (explode("/", $workers) as $substring) {
$col = 0;
foreach (explode(":", $substring) as $value) {
$array[$row][$col] = $value;
$col++;
}
$row++;
}
$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");
foreach ($workers as $worker) {
$worker = explode(':', $worker);
$array[$worker[0]] = $worker[1];
}
Try this code:
<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
$new_arr[]=explode(':',$value);
}
?>
The quick solution is
$results = [];
$data = explode("/", $workers);
foreach ($data as $row) {
$line = explode(":", $row);
$results[] = [$line[0], $line[1]];
}
You could also use array_walk with a custom function which does the second level split for you.
This is another approach, not multidimensional:
parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);
Shorter in PHP >= 5.4.0:
parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);
yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...
$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);
output:
Array
(
[name] => Array
(
[1] => age1
[2] => age2
[3] => age3
)
)

How can I iterate through two arrays at the same time without re-iterating through the parent loop? [duplicate]

This question already has answers here:
php looping through multiple arrays [duplicate]
(8 answers)
Closed 9 years ago.
How can I iterate through two arrays at the same time that have equal sizes ?
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
Not the most efficient, but a demonstration of SPL's multipleIterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$newArray = array();
foreach ( $mi as $value ) {
list($value1, $value2) = $value;
echo $value1 , '-' , $value2 , PHP_EOL;
}
Use a normal for loop instead of a foreach, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
If they're the same size, just do this:
foreach($a as $key => $content){
$contentb = $b[$key];
echo($content."-".$contentb."<br />");
}

Check how many times specific value in array PHP [duplicate]

This question already has answers here:
Count number of values in array with a given value
(8 answers)
Closed 3 years ago.
I have an array named $uid. How can I check to see how many times the value "12" is in my $uid array?
Several ways.
$cnt = count(array_filter($uid,function($a) {return $a==12;}));
or
$tmp = array_count_values($uid);
$cnt = $tmp[12];
or any number of other methods.
Use array_count_values(). For example,
$freqs = array_count_values($uid);
$freq_12 = $freqs['12'];
Very simple:
$uid= array(12,23,12,4,2,5,56);
$indexes = array_keys($uid, 12); //array(0, 1)
echo count($indexes);
Use the function array_count_values.
$uid_counts = array_count_values($uid);
$number_of_12s = $uid_counts[12];
there are different solution to this:
$count = count(array_filter($uid, function($x) { return $x==12;}));
or
array_reduce($uid, function($c, $v) { return $v + ($c == 12?1:0);},0)
or just a for loop
for($i=0, $last=count($uid), $count=0; $i<$last;$i++)
if ($uid[$i]==12) $count++;
or a foreach
$count=0;
foreach($uid as $current)
if ($current==12) $count++;
$repeated = array();
foreach($uid as $id){
if (!isset($repeated[$id])) $repeated[$id] = -1;
$repeated[$id]++;
}
which will result for example in
array(
12 => 2
14 => 1
)

Categories