Correct way of php concatenation - php

Hey is this the correct way to do concatenation? it does not seem to want to work for me!.
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++){
if(${"driver".$i} == $driverrace["fastestlap"]) {
${"driver". $i ."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}

I agree with what is said in the comments. An array is a much better way to handle this.
<?php
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++) {
$driver = "driver$i";
if($$driver == $driverrace["fastestlap"]) {
${$driver."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}
Can be translated into:
<?php
$drivers['bill'] = 0;
$drivers['ted'] = 0;
$drivers['cheech'] = 0;
$drivers['chong'] = 0;
foreach ( $drivers as $driver => &$points ) {
if ( $driver == $race['fastestlap'] ) {
echo "$driver had the fastest lap!";
$points += $driver_points_system['fastestlap'];
$racepoints += $team_points_system['fastestlap'];
break;
}
}
You can obviously do this as a numerative array and replace all of the $drivers[$driverName] assignments to just $drivers[]. I used an associative array to demonstrate that arrays are not only more efficient for this application, they can also be much easier to work with.
I passed the value argument of the foreach by reference, the "&" prefix (similar to a pointer, variable stores the memory address as opposed to the value); this allows you to directly manipulate the value in your logic as opposed to being given a copy of the value and needing to reassign with something similar to a $drivers[$driver] = $points;

Related

dynamic array variable with dynamic values

I am in too much trouble. I need below type of array:-
$val = "abc";
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
I tried below:-
for($i = 1; $i<16; $i++)
{
$arr.$i["besk"] = $val
}
here I've $val. so not to worry on that. But array is not properly creating. Any help would be appreciated.
first define the array as string
like
$arr = 'arr';
then use the foreach
like
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
You need to use variable variables (not recommended)
for($i = 1; $i<16; $i++)
{
${"arr".$i}["besk"] = $val
}
EDIT : #CBroe is right about his comment, you should use an array instead. So the best solution would be to create a two dimensional array like so :
$arr = [];
for($i = 0; $i<15; $i++)
{
$arr[$i]["besk"] = $val
}
The only difference is your array indexes start from 0 now and if you want to have the third value of your array you need this command $arr[2]["besk"]
it is very simple use this:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val
}
Use this approach:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
add new variable
$val = "abc";
$arrName = "arr"; //this one
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
and to call it
for($i = 1; $i<16; $i++)
{
${$arrName.$i}["besk"] = $val
}
ps. you did not create array, you just create 15 array variable with 1 index("besk" index)

How to return array in php?

How to return array in php ? Actually I want to return whole value of $x[] insted of last index of $x[]. Please help me...
<?php
function top() {
require './php/connection.php';
$sql = "SELECT * FROM tbl_add";
$query = mysqli_query($connect, $sql);
$n = 0;
while ($result = mysqli_fetch_assoc($query)) {
$a[$n] = $result['add_id'];
$n = $n + 1;
}
$n = $n - 1;
for ($j = 0; $j < $n; $j++) {
for ($i = 0; $i < $n - 1 - $j; $i++) {
if ($a[$i] > $a[$i + 1]) {
$tmp = $a[$i];
$a[$i] = $a[$i + 1];
$a[$i + 1] = $tmp;
}
}
}
for ($i = 0; $i <= $n; $i++) {
echo $a[$i] . '<br>';
}
$j = 1;
for ($i = 0; $i <= 5; $i++) {
$r = $a[$i];
$sql = "SELECT * FROM tbl_add WHERE add_id='$r'";
$query = mysqli_query($connect, $sql);
$result = mysqli_fetch_assoc($query);
if ($result) {
$x[] = $result['mail'];
return $x[];
}
}
}
?>
return $x[]; is invalid syntax.
In expression $x[] = $result['mail'];, $x[] doesn't mean "the last element of $x". It is just a courtesy of PHP that spares the programmer of writing $x[count($x)]1 instead.
Returning an array is as easy as return $x; (given $x is an array).
Btw, there is no place in your code where $x is initialized as array. You just add values to some variable that doesn't exist, using the array syntax. PHP helps you and creates an array first and stores it in the $x variable but this practice is strongly discouraged. You should add $x = array(); somewhere before you use $x for the first time (outside the loop, of course). For example, you can put it before the line for ($i = 0; $i <= 5; $i++) {.
`
1 This statement is not entirely correct. However, if the values are added to the array using only the $x[] = ... syntax (as it happens in the posted code) then it is correct.
You have to return $x
Then when you call this function $data = top();
Now you get return data of function top to variable name data
// the code below will return $x as it is, independent of what it is. Array, integer, string etc..
Return $x;
// if you need to return two values use:
Return array($x, $y);
// again bit variables are returned as they are.
To call the function and get the values/array use:
$array = top();
Var_dump($array); //should be $x from your function

How to change the value with a variable within a for loop?

I have the following code:
$extraPhoto_1 = get_field('extra_photo_1');
$extraPhoto_2 = get_field('extra_photo_2');
$extraPhoto_3 = get_field('extra_photo_3');
$extraPhoto_4 = get_field('extra_photo_4');
But I would like to rewrite it with a for loop, but I can't figure out how to put a variable within the value field. What I have so far is:
for($i = 1; $i < 5; $i++) {
${'extraPhoto_' . $i} = get_field('extra_photo_ . $i');
}
I've tried with an array like this:
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["$extraPhoto_$i"] = get_field('extra_photo_ . $i');
}
Nothing seems to fix my problem. I'v searched on the PHP website (variable variable).
There is some bug in your code which not allowing. Use 'extra_photo_'. $i instead of 'extra_photo_. $i'
for($i = 1; $i < 5; $i++) {
$extraPhoto_.$i = get_field('extra_photo_'. $i);
}
You can build an array as defined below and than just call extract($myfiles) to access them as variables.
Again your syntax for the get field is incorrect you should append $i after the quotes.
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_".$i] = get_field('extra_photo_'.$i);
}
extract($myfiles);
If you want to create dynamic variable, use below code
for ($i = 1; $i < 5; $i++) {
${'extraPhoto_'.$i} = $_POST['extra_photo_'.$i];
}
if you want to assign variables to array use below code.
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_$i"] = $_POST['extra_photo_'.$i];
/// $myfiles["extraPhoto_$i"] = get_field('extra_photo_'.$i);
}
and than to see if values are assign to new array or not, you can use below code.
echo "<pre>";print_r($myfiles);echo "</pre>";

How to remove duplicate playing cards from player's hand?

I am trying to deal a hand of five cards to a player and score them. My scoring program seems to be working fine, but I am running into the issue of duplicate cards getting dealt from time to time. I tried using a while loop to check for duplicate cards, but this seems kind of hackish. My code is below. Please keep in mind that I am definitely a neophyte, so the simpler the solution the better! Thanks so much.
// create suits array
$suits = array("996", "997", "998", "999");
// create faces array
$faces = array();
$faces[1] = "1";
$faces[2] = "2";
$faces[3] = "3";
$faces[4] = "4";
$faces[5] = "5";
$faces[6] = "6";
$faces[7] = "7";
$faces[8] = "8";
$faces[9] = "9";
$faces[10] = "10";
$faces[11] = "11";
$faces[12] = "12";
$faces[13] = "13";
// create player's hand
$card = array();
for ($i = 0; $i < 5; $i++)
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$card[$i] = $faces[$face_value].$suits[$suit_value];
$counter = 0;
while ($counter < 100)
{
if (in_array($card[$i], $card))
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$card[$i] = $faces[$face_value].$suits[$suit_value];
}
$counter++;
}
print ("<img src=\"../images/4/$card[$i].gif\">");
}
It might be more efficient to simply set up an array that has 52 elements, one for each of the cards.
$cards = range(0,51);
shuffle($cards);
$hand = array();
for ($i = 0; $i < 5; $i++)
{
$hand[$i] = $cards[$i];
}
Note that you can extract the suit and rank of a card $i simply, by doing
$suit = $hand[$i] % 4;
$rank = $hand[$i] / 4;
This will prevent duplicates.
EDIT: Suit and rank were reversed. They should be correct now.
Because you said you like it easy, you could create your arrays with range().
To avoid getting duplicate hands, check the $card array with before assigning the new hand.
the new code would look like:
// create suits array
$suits = range(996, 999);
// create faces array
$faces = range(0, 13);
// create player's hand
$card = array();
while ( count($card) < 5 )
{
$face_value = shuffle($faces);
$suit_value = shuffle($suits);
$newcard = $faces[$face_value].$suits[$suit_value];
if ( in_array($card, $newcard) ) {
$card[] = $newcard;
print ("<img src=\"../images/4/$newcard.gif\">");
}
}
I would definitely create a deck with all 52 cards in it like so:
// create suits array
$suits = range(996, 999);
// create entire deck
$deck = range(0, 51);
shuffle($deck);
// create player's hand
for ($i = 0; $i < 5; $i++) {
$suit_value = $suits[$deck[$i] % 4];
$face_value = floor($deck[$i] / 4) + 1;
print ("<img src=\"../images/4/{$face_value}{$suit_value}.gif\">");
}

Undefined index errors when using plus equal operator

I'm working on another developers old code and there are tons of Notice: Undefined index errors when data is being set using the += operator. Essentially the index is not set yet in the array so the error is generated.
Example:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] += 1;
}
Will generate an error on the first run since the test index is not set yet.
I know I can remove this error with the following code:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
if ( ! isset($myArray['test']) )
{
$myArray['test'] = $myValue;
}
else
{
$myArray['test'] += $myValue;
}
}
However, there are around 50 of things like this to change. Is it worth writing all these isset statements or is there a better way I am not aware of?
EDIT: I should note that the array indexes aren't always the same and sometimes aren't set so I can't preset the index in this circumstance to avoid the error.
This is a bit shorter, but perhaps still a bit complicated if you have many edits.
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
isset($myArray['test']) ? $myArray['test'] += $myValue : $myArray['test'] = $myValue;
}
You could also write a global function (not tested)..
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
increment($myArray['test'], $myValue);
}
function increment(&$var, $inc){
$var = isset($var) ? $var += $inc : $var = $inc
}
If you are using PHP 7 and above, you can use the Null Coalescing Operator to make this code cleaner.
$myArray = [];
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] = $myValue + ($myArray['test'] ?? 0);
}
The benefit here is not only that the code is cleaner, but you're also being more explicit about the default value (0)
Old/Deprecaded/Unrecommended but the shortest solution is
#$myArray['test'] += $myValue;

Categories