Basic PHP concepts (accessing/declaring array variables) - php

$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.

Related

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

PHP - Stop need to create hundreds of variables

I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)

Stuck on PHP to Python Translation

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

How to implode many available to one available using loop for?

How to implode many available to one available using loop for ?
i have many available like
$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;
and then i want to implode to one available
$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,
but i want to using loop for like this
for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}
how can i do ? thank you for every comment ^^
$all_data = implode(',', array($var_1, $var_2, ..., $var_11));
Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.
For the for loop you're trying to write, see the PHP documentation on Variable Variables.
$all_data = '';
for ($i = 1; $i < 12; $i++) {
$all_data .= ${'var_'.$i} . ',';
}

Equivalent of objectAtIndex in PHP

I have an array called followers and I would like to know how I could get the objectAtIndex $a of the array in PHP.
My current code is this, but it doesn't work:
$followers = anArray....
$returns = array();
for ($a = 1; $a <= $numberOfFollowers; $a++) {
$follower = $followers[$a];
echo $follower;
$query = mysql_query("query....");
if (!$query) {}
while ($row = mysql_fetch_assoc($query)) {
}
}
edit--- This is how I get the followers:
$followers = array();
while ($row = mysql_fetch_array($querys)) {
$followers[] = $row['followingUserID'];
}
$numberOfFollowers = count($followers);
Why not do a foreach(), like this?
$followers = array();
$returns = array();
foreach($followers as $index => $follower){
echo $follower;
$query = mysql_query("query....");
if (!$query) {}
while ($row = mysql_fetch_assoc($query)) {
}
}
I don't know what you are cooking with this, but to me, this is a huge cannon shooting towards the DB. Try to optimize your queries into a single one. Don't ever imagine DB fetches with a loop in your mind.
It looks like every element of $followers is a value returned from mysql_fetch_assoc(). Each element will be an associative array, and when you echo it I would expect to see it echoed as the string 'Array', since that is PHP's usual behaviour.
One point to observe is that when you create an empty array using array() and then populate it using assignments of the form $myarray[] = ..., the resulting array will be zero-indexed. That is, the keys of the array will start at 0, not at 1. So instead of for ($a = 1; $a <= $numberOfFollowers; $a++) {, you need to use for ($a = 0; $a < $numberOfFollowers; $a++) {, or go for the solution suggested by #Shef and use foreach.
Your problem might arise because $followers contains only one element, and because of the off-by-one error, you are not seeing any output. Turn on error reporting by adding this line at the start of your script:
error_reporting(E_ALL & ~E_STRICT);
If I am right then with your current code, you should see a Notice: Undefined index: 1 ...

Categories