Stuck on PHP to Python Translation - php

I'm attempting to translate some PHP code to Python and I'm stuck on the 4th line in the following code (included for context):
$table = array();
for ($i = 0; $i < strlen($text); $i++) {
$char = substr($text, $i, $look_forward);
if (!isset($table[$char])) $table[$char] = array();
}
If array() is used to create an array in PHP, what is $table[$char] = array() doing? Creating a new array inside an existing array? Or is it extending the array?
What is this accomplishing? What would be the Python equivalent to this?
if (!isset($table[$char])) $table[$char] = array();

Seems to me, you should use another data structure than list as table variable. I suppose that dict should be nice for the purpose.
I've just made a quick try to mimic your PHP code in Python:
table = {} # use dictionary instead of list here
for char in text:
if char not in table:
table[char] = []
# do your stuff with table[char]
pass
Also, I suggest you look into https://docs.python.org/3/library/collections.html#collections.defaultdict
With the class the code could be rewritten in the following way:
import collections
table = collections.defaultdict(list)
for char in text:
# do your stuff with table[char], empty list is created by default
pass

if (!isset($table[$char])) $table[$char] = array(); is setting value of $table[$char] variable as array() if $table[$char] is not set yet
$table is empty array, so it has not contain "$char" as key so its checking if $table[$char] is set or not , if not then set its ($table[$char]) value as array().
if you put your code like
$table = array();
for ($i = 0; $i < strlen($text); $i++) {
$char = substr($text, $i, $look_forward);
$table[$char] = array();
}
then it gives notice like Notice: Undefined index: $char in

Related

Foreach over an array

I'd like ask on my problem with formatting array. I'm importing data to system from .XLSX. Function return me array which one looks like:
Array Index
My question is how I can insert this data to table if I know array with index 1 and with number 1 is Name e.t.c?
I can write SQL but I can't write foreach. I already tried make some foreach but without success.
Thank you one more time
Here is solution:
/** #var int $count */
$count = count($spreadsheet);
$s = array();
for($i = 1; $i < $count; ++$i) {
$s = $spreadsheet[$i];
}
return $s;

How to improve array_rand() function with PHP?

I use the array_rand PHP function with an array. I use it with a data fixture function wich load a set of data in a loop like this:
$random_values = array();
for ($i = 0; $i < 20; $i++) {
$random_values[] = array_rand(["1","2","3","4","5"]);
}
My result is quite always "1" in the $random_values array, the native
PHP function seems not really random, Is there another stuff to do to
improve the randomization of my algorithm ?
Notice I already know there is an official documentation here, http://php.net/manual/fr/function.array-rand.php.
How's it going? So, with array_rand, it actually returns a random key within an array. Your current code does not put the random key value into the array you want to randomize. ie echo $random_value[$random_key]... See example below, hope this helps
$random_values = array("1","2","3","4","5");
for ($i = 0; $i < 20; $i++) {
$key = array_rand($random_values);
echo $random_values[$key] . "\n";
}

php not able to get array value

I have this problem where I can't get the value from the array in the for loop but I can access it in the while loop.
I can't seem to find a answer online, so help would be much appreciated.
while ($pos = strpos($logTxt, $char, $pos))
{
$t++;
$pos += strlen($char);
$positions[$t] = $pos;
}
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[2];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
I think that this could be pretty easily fixed by using a foreach loop instead of a for loop, because it is an array.
foreach($positions as $position) {
$beginLine = $lastEndLine;
$endLine = $position;
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
If you want to use a for loop still, I believe your problem is you are only referencing the 3rd position of the array (Key 2, as arrays start at 0), not what the loop is pointing to. You could fix it by doing this
for($i = 0; $i < sizeof($positions); $i++)
{
$beginLine = $lastEndLine;
$endLine = $positions[$i];
$textToEcho = substr($logTxt,$beginLine,$endLine);
$lastEndLine = $endLine;
}
Your $endLine always has third element from array, because of $positions[2]. Try changing it to $positions[$i]
You base problem is using constant index in $positions[2]. But your 1st line in for loop $beginLine = $lastEndLine; will always fail because $lastEndLine is not defined yet. You can use smth like
// beginLine // endLine
$textToEcho = substr($logTxt, $positions[$i-1], $positions[$i]);
of course you need $positions[-1] set to 0 before your first loop or smth like this (it's not clear what's happening before)
UPD I've tried your code and concluded
it will not work at all if $char is the first occurence in $logTxt
it does the nearly the same as explode() function

Basic PHP concepts (accessing/declaring array variables)

$result = array();
for ( $i = 10; $i < 101; $i = $i + 10 ){
$result[] = $i;
}
echo implode(", ", $result);
Hello...I'm new to PHP, and this really confused me, declaring a variable array even the code will work without it.
I've found this code here in the forum, regarding the removal of the comma in a for loop. I was wondering what variable is called when it is echoed? Is it the $result = array() or the $result[]? I've tried to remove the $result = array(); and the code still work, is that mean, is it ok to just remove the $result = array();? Does it have some coding issues if it is removed?
The line $result = array(); is used to declare an array.
It's a better approach to use this especially when you have some other previously specified variable $result storing some other value. Mentioning this first line will reset any previously assigned value to $result and declare it as an array datatype.
$result[] = $i; means the value of $i keeps apppending to $result every time.

PHP: Pass dynamically created variables to a built-in function

DESCRIPTION OF PROBLEM:What I am trying to do is pass dynamically created variables from a loop to a function in php. More specifically, I used a for loop to create variables and assign data to them. Then use a for loop to string all the variables together. Then pass the string to the multisort_array function and explode the string to use the variables. I'm not sure what I am doing wrong.
QUESTION:How would I pass a bunch of dynamically created variables to a sort function without knowing how many I am going to create? That is my delema.
CODE:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
// explodes first value of $arr2
$tmp = explode("::",$arr2[0]);
// determines how many dynamic variables to create
for($k=0;$k<count($tmp);$k++){
${"mArr".$k} = Array();
}
// loops thru & assigns all numbers to mArr0
// loops thru & assigns all names to mArr1
for ($k=0;$k<count($arr2);$k++){
$tmp = explode("::",$arr2[$k]);
for($l=0;$l<count($tmp);$l++){
${"mArr".$l}[$k] = $tmp[$l];
}
}
// Will add a for loop to combine the variables into string
$param = "$mArr1,$mArr0";
// send the string to array_multisort to be sorted by name
// have tried the following options:
// 1. array_multisort(explode(",",$param));
// 2. call_user_func_array(array_multisort,explode(",",$param));
// both do not sort & give me an error.
Thank you in advance for your help. I am open to any suggestions on other ways this can be accomplished, but I would like it to be in the php code if at all possible.
Just pass the array itself into the function.
arraySort($array);
Sort the array before splitting it in to other arrays using a custom sorting function:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
//Split the input in place, you could also use a new array for this
for($i = 0;$i < count($arr2);$i++)
{
$arr2[$i] = explode("::",$arr2[$i]);
}
//Define our new sorting function
function sort_second_item($a,$b)
{
return strcmp($a[1],$b[1]);
}
var_dump($arr2);
usort($arr2,'sort_second_item');
var_dump($arr2);
$rotated = array();
//Rotate $arr2
for($i = 0; $i < count($arr2); $i++)
{
for($j = 0;$j < count($arr2[$i]); $j++)
{
if(!isset($rotated[$j]))
{
$rotated[$j] = array();
}
$rotated[$j][$i] = $arr2[$i][$j];
}
}
var_dump($rotated);

Categories