I want to remove empty elements from an array. I have a $_POST-String which is set to an array by explode(). Then I'am using a loop to remove the empty elements. But that does not work. I also tried array_filter(), but with no succes. Can you help me? See Code below:
$cluster = explode("\n", $_POST[$nr]);
print_r ($cluster);
echo "<br>";
for ($i=0 ; $i<=count($cluster);$i++)
{
if ($cluster[$i] == '')
{
unset ( $cluster[$i] );
}
}
print_r ($cluster);
echo "<br>";
Result:
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => [5] => )
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => )
Empty elements can easily be removed with array_filter:
$array = array_filter($array);
Example:
$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
[item_1] => hello
[item_3] => world
)
*/
The problem ist that the for loop condition gets evaluated on every run.
That means count(...) will be called multiple times and every time the array shrinks.
The correct way to do this is:
$test = explode("/","this/is/example///");
print_r($test);
$arrayElements = count($test);
for($i=0;$i<$arrayElements;$i++)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
An alternative way without an extra variable would be counting backwards:
$test = explode("/","this/is/example///");
print_r($test);
for($i=count($test)-1;$i>=0;$i--)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
What if you change:
for ($i=0 ; $i<=count($cluster);$i++) { if ($cluster[$i] == '') { unset ( $cluster[$i] ); } }
to
for ($i=0 ; $i<=count($cluster);$i++) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } }
Related
I have a product variation combination ID. Hyphen (-) The characters between the strings represent the variation options id.
I want to make copies of other IDs for free variation options based on the main combination ID.
My codes:
function find_replace($array, $find, $replace){
$array = array_replace($array,
array_fill_keys(
array_keys($array, $find),
$replace
)
);
return $array;
}
function get_var_key($array, $value){
$key_name=false;
foreach ($array as $n=>$c)
if (in_array($value, $c)) {
$key_name=$n;
break;
}
return $key_name;
}
$get_free_keys = array(
"var1" => array(
"free1",
"free2"
),
"var2" => array(
"free3",
"free4"
)
);
$main_combine = "a1-b1-free1-c1-d1-free3";
$main_combine_explode = explode("-", $main_combine);
for($i=0; $i < count($main_combine_explode); $i++){
$get_key_by_value = get_var_key($get_free_keys,
$main_combine_explode[$i]); // return "var1" or "var2"
foreach($get_free_keys[$get_key_by_value] as $values){
$find_combine = find_replace($main_combine_explode,
$main_combine_explode[$i], $values);
$combines[] = implode("-", $find_combine);
}
}
print_r($combines);
Wrong result:
Array
(
[0] => a1-b1-free1-c1-d1-free3 // main combine (ok)
[1] => a1-b1-free2-c1-d1-free3 // ok
[2] => a1-b1-free1-c1-d1-free3 // wrong
[3] => a1-b1-free1-c1-d1-free4 // wrong
)
Result is incorrect
I want to get the following result:
Array
(
[0] => a1-b1-free1-c1-d1-free3-e1 // $main_combine
[1] => a1-b1-free1-c1-d1-free4-e1
[2] => a1-b1-free2-c1-d1-free3-e1
[3] => a1-b1-free2-c1-d1-free4-e1
)
or
Array
(
[var1] => Array
(
[0] => a1-b1-free1-c1-d1-free3 // $main_combine
[1] => a1-b1-free2-c1-d1-free3
)
[var2] => Array
(
[0] => a1-b1-free1-c1-d1-free4
[1] => a1-b1-free2-c1-d1-free4
)
)
Thank you.
You can use get_combinations and str-replace and do:
$template = "a1-b1-#FIRST#-c1-d1-#SECOND#-e1";
foreach (get_combinations($get_free_keys) as $e) {
$res[] = str_replace(['#FIRST#', '#SECOND#'], $e, $template);
}
Live example: 3v4l
I have the following code :
public static function getNatureAndSuffix()
{
foreach (Finder::load('all.yml') as $s => $c) {
$a_games[] = array($c['n'] => $s);
}
return $a_games;
}
The result is :
Array(
[90] => Array
(
[731] => Test1
)
[91] => Array
(
[732] => Test2
)
[92] => Array
(
[735] => Test3
)
)
But I want to get :
Array(
[731] => Test1
[732] => Test1
[735] => Test3
)
So the idea is to obtain an array key=>value. Can you help me please ? Thx in advance
public static function getNatureAndSuffix()
{
foreach (Finder::load('all.yml') as $s => $c) {
$a_games[$c['n']] = $s;
}
return $a_games;
}
explanation:
with: array($c['n'] => $s) you are creating a new array in a array($a_games) what you don't want.
So if you id the index of the first array with the id you get from the loop and give it the value you get from the loop you end up with only a single array.
So the line would be:
$a_games[$c['n']] = $s;
You are setting a new array with those value.
By $a_games[] = array($c['n'] => $s);, it would set as nested array.
Simply do -
$a_games[$c['n']] = $s;
Then the key would be $c['n'] & value be $s in $a_games.
Or you can also do without loop -
$temp = Finder::load('all.yml');
$a_games = array_combine(
array_keys($temp),
array_column($temp, 'n')
);
Note : array_column() is supported PHP >= 5.5
I want to remove the empty and null values from $listValues array.
Here I am removed the empty values using array_filter.
Sample Code:
$listValues = array("one", "two", "null","three","","four","null");
$resultValues = array_filter($listValues);
echo "<pre>";
print_r($resultValues);
echo "</pre>";
Result:
Array ( [0] => one [1] => two [2] => null [3] => three [5] => four [6] => null )
But I want
Array ( [0] => one [1] => two [3] => three [5] => four )
Any advice greatly appreciated.
try this : use array_diff() function compares the values of two (or more) arrays, and returns the differences. to remove null and "" . if you need to remove some more field then add that values inside the array
<?php
$listValues = array("one", "two", "null","three","","four","null");
echo "<pre>";
$a=array_values(array_diff($listValues,array("null","")));
print_r($a);
echo "</pre>";
?>
output :
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
refer
http://www.w3schools.com/php/func_array_diff.asp
Try array_filter with second parameter as a user defined function like this:
$listValues = array("one", "two", "null","three","","four","null");
print_r(array_filter($listValues, "filter"));
function filter($elmnt) {
if ($elmnt != "null" && $elmnt != "" ) {
return $elmnt;
}
}
Use this code, First I corrected the index of an array, then unset null values from an array then corrected array indexes again:
$listValues = array("one", "two", "null","three","","four","null");
$listValues = array_values($listValues);
$temp = $listValues;
for($loop=0; $loop<count($listValues); $loop++){
if($listValues[$loop] == "" || $listValues[$loop] == "null"){
unset($temp[$loop]);
}
}
$listValues = $temp;
$listValues = array_values($listValues);
echo "<pre>";
print_r($listValues);
echo "</pre>"; die;
But, if you want same indexes to get this output:
Array ( [0] => one [1] => two [3] => three [5] => four )
Then don't use this before <pre>:
$listValues = array_values($listValues);
I have the following array imported from a CSV:
Array
(
[0] => Array
(
[0] => QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014
)
[1] => Array
(
[0] => January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200
)
[2] => Array
(
[0] => ;;17
[1] => 30%;8%;5
[2] => 30%;5%;4
[3] => 80%;4
[4] => 50%;4
[5] => 30%;4
[6] => 20%;4%;3
[7] => 20%;3%;2
[8] => 70%
)
[3] => Array
(
[0] => TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200
)
[4] => Array
(
[0] => ;;17
[1] => 30%;7
[2] => 95%;5
[3] => 26%;5%;4
[4] => 76%;4
[5] => 55%;4
[6] => 35%;4
[7] => 17%;4%;3
[8] => 23%;2
[9] => 98%;2
[10] => 75%
)
So,
I would like to get rid of all arrays containing "% and TOTAL".
I thought to loop through and unset the matching case:
$remove ="TOTAL";
foreach ($csv as $key => $value){
if (in_array($remove,$value[$key])){
unset($value[$key]);
}
}
This is the error I got:
Warning: in_array() expects parameter 2 to be array, null given
My PHP Version 5.3.10
Would you do it that way or would you use the array_filter?
I am browsing since 2 hours the forum but I could not find any hint helping me out.
Cheers.
You can try by preg_replace for removing TOTAL & %. If you want to remove the element from array then use unset & finally use array_filter for removing null elements.
$newArr = array();
foreach($arr as $key=>$value){
foreach($value as $k=>$v){
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
}
//Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
//output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
In your case:
foreach ($csv as $subArray)
{
for ($i = 0, $len = count($subArray); $i < $len; $i++)
{
if (strpos($subArray[$i], $remove) !== false)
unset($subArray[$i])
}
}
Comments:
strict comparasion for strpos, if we use !=, then 0 position would be equals to false.
inner loop is "for-loop" bevause it's better to avoid changing content of array inside foreach.
$arr[][] = ("QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014");
$arr[][] = ("January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200");
$arr[] = array(";;17","30%;8%;5","30%;5%;4","80%;4","50%;4","30%;4","20%;4%;3","20%;3%;2","70%");
$arr[][] = ("TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200");
$arr[] = array("30%;7","95%;5","26%;5%;4","76%;4","55%;4","35%;4","17%;4%;3","23%;2","98%;2","75%");
$newArr = array();
foreach($arr as $key=>$value) {
foreach($value as $k=>$v) {
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
unset($arr[$key]); // IT does not unset ARR[2] ARR[3] and ARR[4] containing TOTAL & %
}
Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
Output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
I did create exactly the same ARRAY as imported from CSV.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.
I am fetching some data from the db and then push them to an array. I need to find the count of some strings and print out the result (count) in an efficient way:
Array
(
[0] => q1-1,q2-2,q3-2,q4-1,q5-2,q6-3,q7-1,q8-4,
[1] => q1-1,q2-2,q3-1,q4-3,q5-3,q6-3,q7-2,q8-1,
[2] => q1-1,q2-1,q3-1,q4-1,q5-1,q6-2,q7-2,q8-2,
[3] => q1-3,q2-1,q3-1,q4-1,q5-2,q6-3,q7-1,q8-1,
[4] => q1-2,q2-2,q3-3,q4-1,q5-3,q6-3,q7-1,q8-1,
[5] => q1-1,q2-2,q3-3,q4-1,q5-2,q6-3,q7-1,q8-1,
[6] => q1-3,q2-1,q3-1,q4-3,q5-2,q6-3,q7-2,q8-4,
[7] => q1-2,q2-2,q3-3,q4-1,q5-2,q6-5,q7-1,q8-1,
[8] => q1-1,q2-1,q3-2,q4-3,q5-3,q6-5,q7-1,q8-1,
[9] => q1-2,q2-1,q3-1,q4-1,q5-3,q6-3,q7-1,q8-1,
[10] => q1-3,q2-2,q3-3,q4-3,q5-4,q6-3,q7-1,q8-1,
...
)
Sample data is above.
I need to know how many occurences of q1-1, q1-2 ... q8-4 is in the array and print out readable version. Ex. The are 23: q1-1, 412: q1-2 and so on.
I was going to create an array of each string that needs to be searched that iterate through the array. For every result increment the resultVariable for that string but I'm not sure if that's the best way.
Suggestions?
Pretty simple, loop on your array, create sub arrays, and create a counter array:
$counts = array () ;
foreach ( $your_array as $row ) {
$sub = explode(',', $row);
foreach ( $sub as $subval ) {
if ( array_key_exists ( $subval, $counts ) ) {
$counts[$subval] ++ ;
} else {
$counts[$subval] = 1 ;
}
}
}
Here is $counts:
Array (
'q1-1' => 23,
'q1-2' => 9,
// and so on....
);
Try:
$arr = array(...); //your array
$count = array();
foreach($arr as $v) {
$substr = explode(',', $v);
foreach($substr as $m) {
if(strstr($v, $m) !== FALSE)
$count[$m]++;
}
}
Printing the counts,
foreach($count as $k => $v)
echo "Count for '$k': ". $v;