How can I echo implode the $result with, and on the same line, without function applied? - echo

How can I echo implode the $result with, and on the same line, without function applied?
The code I have so far is:
else {
echo implode('<br/>', array_map('convertToBinaryString, $result));
}
which produces:
00000
00001
00011
and so on, the NOT binary variants are: 0, 1, 3, etc....
i'd like it to be printed as:
00000 is 0
00001 is 1
00011 is 3
I tried this:
echo implode('<br/>', array_map('convertToBinaryString, $result));
echo implode('<br/>', $result);
but that produces
00000
00001
00011
...
0
1
3
...

like so:
foreach ($test as $t)
{
echo $t."\t". bindec($t).'<br>';
}

Instead of convertToBinaryString() call a new function that concatenates the decimal representation and the binary representation and returns one line of text:
$result = [ 0, 1, 3, 6, ];
$output = array_map(
function ($item) {
// Use $item to generate one line of output
return convertToBinaryString($item).' is '.$item;
},
$result
);
echo(implode('<br/>', $output));
Or you can do it in a plain foreach loop way:
$result = [ 0, 1, 3, 5 ];
foreach ($result as $item) {
echo(convertToBinaryString($item).' is '.$item."<br/>");
}

Related

How do I find and get value from multi dimensional array in powershell?

Basically I have an array that looks something like
areaCodes = # (
#("310", "LA"),
#("212", "NY"),
#("702", "LV")
)
I would like to have it so that for example if I have a variable $code = $212 Find if it is in the list, and if is, get the value associated with it.
Something like
if($areaCodes.contains($code))
{
WRITE-HOST $areaCodes[1]
}
and this would output NY
How do I do this in powershell? Or is there are more efficient way to do this?
You need to enumerate all arrays inside your array for this to work, for example:
($areaCodes | Where-Object { $_ -contains $code })[1] # => NY
Or using an actual loop:
foreach($array in $areaCodes) {
if($array -contains $code) {
$array[1]
break
}
}
But taking a step back, a hash table seems a lot more appropriate for your use case:
$code = 212
$areaCodes = #{
310 = "LA"
212 = "NY"
702 = "LV"
}
$areaCodes[$code] # => NY

How to stop Powershell from flattening parameter of jagged array?

I created a hashtable representing the structure of the file I'm extracting data from
# schema of the data stored in the file
$RecordSchema = #{
Header = #(
#("EmployerName", 2, 30)
#("ApplicableMonth", 32, 6)
#("EmployerIDNumber", 38, 10)
)
}
# function to extract data from the file based on the $schema
function Map-Field ($row, $schema) {
$mappedRow = #{}
foreach ($field in $schema) {
$fieldName = $field[0]
$fieldPosition = $field[1]
$fieldSize = $field[2]
$value = $row.Substring($fieldPosition, $fieldSize)
$mappedRow[$fieldName] = $value
}
[PSCustomObject]$mappedRow
}
function Set-RecordHeader($record, $recordRaw) {
$record["Header"] = Map-Field $recordRaw[0] $RecordSchema["Header"]
$record
}
When I run the script, $schema gets the flattened version of the schema $RecordSchema.Header I've passed.
I've added comma before the parameter $RecordSchema["Header"] yet I got an array of single-item array and that item contains the flattened version of the schema I'm passing.
$record["Header"] = Map-Field $recordRaw[0] (,$RecordSchema["Header"])
I've just discovered that for some reason, I need to add a comma at the end of each array
$RecordSchema = #{
Header = #(
#("EmployerName", 2, 30), # this
#("ApplicableMonth", 32, 6), # and other comma matter
#("EmployerIDNumber", 38, 10)
)
}
I verified it by running the following
$a = #(
#(1, 2, 3)
#(4, 5, 6)
)
$b = #(
#(1, 2, 3),
#(4, 5, 6)
)
$a.Length # returns 6
$b.Length # returns 2
I've thought PowerShell will think that passing a new line means another entry :-(

Powershell loop with numbers to alphabet

I need help with the following:
Create a for loop based on the conditions that the index is initialized to 0, $test is less than 26, and the index is incremented by 1
For each iteration, print the current letter of the alphabet. Start at the letter A. Thus, for each iteration, a single letter is printed on a separate line.
I am not able to increment the char each time the loop runs
for ($test = 0; $test -lt 26; $test++)
{
[char]65
}
I have tried multiple attempts with trying to increment the char 65 through 90 with no success.
Is there an easier way to increment the alphabet to show a letter for each loop that is ran?
You can sum your loop index with 65. So, it'll be: 0 + 65 = A, 1 + 65 = B ...
for ($test = 0; $test -lt 26; $test++)
{
[char](65 + $test)
}
PS2 to PS5:
97..(97+25) | % { [char]$_ }
Faster:
(97..(97+25)).ForEach({ [char]$_ })
PS6+:
'a'..'z' | % { $_ }
Faster:
('a'..'z').ForEach({ $_ })
The following example does not assume 'A' is 65 and also allows you to change it to whatever starting drive you desire. For example, to start with 'C' and go to 'Z':
$start = 'C'
for ($next = 0; $next -lt (26 + [byte][char]'A' - [byte][char]$start); $next++) {
[char]([byte][char]$start + $next)
}
Here's a way to find the first available drive. It checks drives E to Z, and stops on the first available one:
101..(97+25) | % { if(!( get-psdrive ([char]$_ ) -ea 0 ) ) {$freedrive = ([char]$_ ); break} }
$freedrive

Convert string to int array in PowerShell

I'm trying to convert a string that looks like this,
2,3,4,5,6,20..30
to an array of integers. Here is the code I currently have:
[string]$a = "2,3,4,5,6,7"
[array]$b = $a.split(",")
[array]$c = foreach($number in $b) {([int]::parse($number))}
Which works, but not for the range of 20..30. How do I get that part working?
You can use the Invoke-Expression cmdlet to interpret the 10..30 bit, if the [int]::Parse() method call fails.
Here is a complete, working sample.
[string]$a = "2,3,4,5,6,7,10..30";
[array]$b = $a.split(",");
[array]$c = foreach($number in $b) {
try {
[int]::parse($number)
}
catch {
Invoke-Expression -Command $number;
}
}
$c;
One-liner (just for fun):
$c = "2,3,4,5,6,7,10..30".split(',') | % {iex $_}
Inside of a string, your .. is taken as-is and is not expanded to a range.
So $a = "1 .. 5" is actually 1 .. 5 and not 1, 2, 3, 4, 5.
To make your program work, you will have to tokenize not only on , but also on .. and then expand.

Problem with Hash of Array

Hi all
I got the problem that i cannot return the value and key in the hash of array
sub nextWords{
for my $language(0 .. $#language )
{
my $eng = $db->selectall_arrayref("select word from words
left outer join language
on words.languageId = language.languageId
where words.languageId = $language
order by word asc
;"); # #language[$id] limit 10 offset $currentOffset
#%returnArray2d = (#language[$language] =>[#$eng] );
$returnArray2d{#language[$language]} = [#$eng];
}
return %returnArray2d;
}
I cannot really return all the list of words
my %newwordsList =NextWords();
foreach my $key(keys %newwordsList)
{
print "here you are 2 : " . $key . "\n";
for my $ind(0 .. #{$newwordsList{$key}}){
print "dzo" . $newwordsList{$key}[$ind] . "\n";
}
}
output: $key ==> 132 not 123
and the word cannot be printed.. it just prints some
ARRAY(0x320d514)
ARRAY(0x320d544)
ARRAY(0x320d574)
ARRAY(0x320d5a4)
ARRAY(0x320d5d4)
ARRAY(0x320d604)
Please help.. thanks
It looks like you're not setting up %returnArray2d correctly.
Assuming that #language contains the language ids you want, instead of:
$returnArray2d{ #language[$language] } = [#$eng];
You'll want this:
$returnArray2d{ $language[$language] } = [#$eng];
Also, you should avoid using the same name for an array and a scalar value (it works, but it's confusing) (see #language / $language in your code).
Lastly, you are correctly iterating through each key of %newwordsList, however, you will want to subtract 1 from the iteration, so that you don't go past the end of the array:
for my $ind ( 0 .. #{ $newwordsList{$key} } ) {
Should be:
for my $ind (0 .. #{ $newwordsList{$key} } - 1) {
Or (as David pointed out in the comments), you can do:
for my $ind ( 0 .. $#{ $newwordsList{$key} } ) {