Retrieving values crossing arrays gives unlogic result - php

In Drupal context, while printing checked exposed filters in a somehow standard code snippet, I can't print more than one value, and I can't find the missing logic of my foreach loop :
<?php
foreach ($exposed_filters as $filter => $value) {
if ($filter == 'foo') {
$field = field_info_field('field_foo');
$allowed_values = list_allowed_values($field);
//returns an array with 14 string values & numeric keys
//e.g array(0=>'bla', 1=>'bar', 2=>'xx', 3=>'yy')
$h = explode(',', $value);//returns checked ids of foo filter e.g array(0 => 2, 1=>3)
$exp_heb = '';
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[$v] . ', ';
}
$exp_heb = substr($exp_heb, 0, -2);
print $exp_heb;
}
}
?>
Should return : xx, yy but I get xx,,
I checked step by step printing out my arrays, values... everything's looks fine but result is wrong. Do I need a rest ???
This is dpm($allowed_values) output

May be this line cuts your output?
$exp_heb = substr($exp_heb, 0, -2);

I got it working. I have to get the integer value of my variable, before passing it as a key :
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[intval($v)] . ', ';
}
For a reason I would be glad to be taught, even if it's always an id, and prints out a number, first time it's passed as integer, but then not.

Related

Convert array to decimal

I have this code:
public function get_names($number){
$names = array(
'None',
'Anton',
'bertha',
'Cesa',
'Dori',
'Egon',
'Frank',
'Gollum',
'Hans',
'Kane',
'Linus',
'Moose',
'Nandor',
'Oliver',
'Paul',
'Reese');
$bin = strrev(decbin($number));
$len = strlen($bin);
$output = array();
foreach(str_split($bin) as $key=>$char)
{
if ($key == sizeof($names)){
break;
}
if($char == 1)
{
array_push($output,$names[$key]);
}
}
return $output;
}
When I now call the function with number - let's say - 32256 I would get an array with "Kane, Linus, Moose, Nandor, Oliver, Paul".
Can anyone tell me what I would have to do when I want to give a certain names array and wanna get the number as a result where the certain bits are included? So exactly the other way around.
I found that code somewhere which works fine. But I need it vice versa.
Thanks in advance!
Andreas
EDIT: I want to know the decimal number when I e.g. have an array with "Anton, bertha,Cesa". I want to store those in a database instead of storing arrays with names each time. And when I need the names I just take the decimal number from database and use my function to get my name arrays.
If you just take the position in your $names array as being the bit position, you raise 2 to this position to give it the correct bit position and keep a running total of the items found...
$input = ["Cesa", "Gollum", "Hans"];
$output = 0;
foreach ( $input as $digit ) {
$output += pow(2,array_search($digit, $names ));
}
echo $output; // 392
with
$input = ["Kane", "Linus", "Moose", "Nandor", "Oliver", "Paul"];
gives
32256
Or as Barmar points out in his comment, you can save the lookup by inverting the names array using array_flip() which will mean that looking up each key will give the position in the array...
$output = 0;
$names = array_flip($names);
foreach ( $input as $digit ) {
$output += pow(2,$names[$digit]);
}
echo $output;

How to access PHP values in array like ["val1","val2","val3"] in loop

I have a problem to get values from single square brackets array. Getting this
//$_POST["values"] == ["val1","val2","val3"]
$val = $_POST["values"];
I want something like:
foreach( $val as $value ) {
$valget = $value;
//need to get all values like $valget = "val1";
}
Thank you very much!
UPDATE:
What Im trying to get?
Values passed as $_POST from filemanager
How I want to proceed?
I wnat for each every result of post save into database
And still saving all as array into database to single row, I need for each record new row.
Database
Ok so this is your var with all $_POST values :
$val = $_POST["values"];
This is what you do :
foreach($val as $value) {
$valget = $value;
}
So each time $valget will be erase by the next $value
// First loop : $valget == "val1"
// Second loop : $valget == "val2"
// Third loop : $valget == "val3"
So at the end if you do echo $valget; you will have the last result : $valget == "val3"
If you want to get each, here is some solution :
1/ Echo each value :
foreach($val as $value) {
echo $value . "<br>";
}
This way you will output
val1
val2
val3
2/ Doing nothing since $val is already an array with all the value :
$val = $_POST["values"];
$val = array(
0 => "val1",
1 => "val2",
2 => "val3"
);
So you can access each value with :
$val[0] == "val1";
$val[1] == "val2";
$val[2] == "val3";
3/ Change the key if you want to to find them an other way :
// New array
$valget = array();
// Create a new index
$index = 1;
foreach($val as $value) {
$valget[$index] = $value;
$index++;
}
This way you will have :
$valget[1] == "val1";
$valget[2] == "val2";
$valget[3] == "val3";
OK got it!
Now I want to share answer with world, because there may be someone else who will face same problem as I had.
After everything I tried only working was:
$numbers = json_decode($_POST['file_img']); //post images from <form> and decode array
foreach($numbers as $index => &$number){
++$number; # we are incrementing the original value
echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
so now $number = "every single image";
Now save to db or whatever..
}
This answer was found here: https://stackoverflow.com/a/47266239/4928816
So If anyone will need to pass variables from standalone responsivefilemanager to PHP as I needed (http://www.responsivefilemanager.com/demo.php), you may use this code to do so.
Thanks everyone who tried to help me!

Displaying proper element from foreach

I want to echo one element of the array like sum1. But I only get one letter like s. Please solve this problem.
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value[0];
echo $value[1];
}
If you want to just echo 1 item from that array, you should to it like this:
echo $nums[0];
If you want to loop through all of them, and show each, do it like so:
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value."<br>";
}
What you did wrong
You had already looped through the array, so you had a string. You can select the first letter from a string like in this example:
$string = "A string";
echo $string[0];
Will return A, as it's the first index of that string. That is essentially what you did in your loop.
You made your String an array, and it showed the index's you selected to be shown. You can read this where the questions asks how to do this. I hope this gives some more clearity.
If you want every element of array,
then,
For your array,
$nums = array("sum1", 100, 200);
$nums[0] will be sum1
$nums[1] will be 100
$nums[2] will be 200,
Now your loop,
foreach ($nums as $value) {
// here echo $value values are like 'sum1', 100, 200 will be printed.
// by default string will be considered as array,
// if you print $value[0], $value[1], $value[2], $value[3] for sum1, it will return, s, u, m, 1 respectively.
// and integers will be considered as pure value, which you will get in $value only, not in $value[0], ....
}
I hope I explained your concern.
Thanks.

PHP - Search array for string

I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Categories