Assign a value conditionally after array is set with PHP - php

If I wanted to do something like this:
<?php
$numbers = array(
"a_pos" => 0,
"b_pos" => 2,
"c_pos" => 3
);
if ($numbers["a_pos"] == 0)
$a_pos_txt = TRUE;
if ($numbers["b_pos"] == 0)
$b_pos_txt = TRUE;
if ($numbers["c_pos"] == 0)
$c_pos_txt = TRUE;
?>
(Just assign TRUE to $a_pos_txt because it is equal to 0)
What would be that smart way to do it? I´m sure there must be a way to do it in "one step".
Thanks in advance!!
Please ask for any needed clarificarion.

Not really sure what you're trying to accomplish, as there may be a better approach overall, but to answer your question, you can skip the if statements like so:
$a_pos_txt = $numbers["a_pos"] == 0;
$b_pos_txt = $numbers["b_pos"] == 0;
$c_pos_txt = $numbers["c_pos"] == 0;

If the $numbers is an array, you can do a loop to avoid repeating the similar pattern,
such as
foreach ($numbers as $key=>$val)
{
if ($val==0)
{
${$key."_txt"}=true;
}
}

Related

I need to check the arrays having same objects or more than same in php

I have variable in php , first is $needed and second is $whatwehave so the objects in arrays is like that =>
$needed=['name','family','job'];
$whatwehave=['name','family','job'];
The thing that i want is available using for but I am looking for a better way.
The thing that i want is checking if the needed arrays exist in $whatwehave say 0 and if its not exist say 1 and if you don't know what is the needed array its stacked in $needed its very simple and i think there is a code in PHP for doing this like in_array($array1,$array2) or something else
My way is this :
$error=0;
for($i=0;$i<=(count($needed)-1);$i++){
if(!in_array($needed[$i],$whatwehave)){
$error=1;
}
}
echo $error;
The way that i looking for is something like that:
if(in_array($first_array,$second_array)){echo 0;}else{echo 1;}
Use function array_diff()
echo array_diff($needed, $whatwehave) ? 1 : 0;
https://www.php.net/manual/ru/function.array-diff.php
<?php
function check_similar($actual, $expected) {
if(!is_array($actual) && !is_array($expected))
return false;
$minLength = count($actual);
if(count($expected) < $minLength)
$minLength = count($expected);
$index = 0;
foreach($actual as $arr) {
if(in_array($arr, $expected))
$index++;
}
if($index >= $minLength)
return true;
return false;
}
$arr1 = ['1','2','3'];
$arr2 = ['1','2','3','4'];
var_dump(check_similar($arr1, $arr2));

PHP store a value from a While loop in an associative manner for external use?

This is only a personal project. So yes, it's using mysql, but it's not commercial and only running on localhost. So, not really imperative I update it to mysqli or anything. I'm also not a developer and dabble with php for personal databases. So, forgive me if my code is horrendous, I'm eager to improve if you'd care to share.
I've constructed a while loop to fill arrays. This allows me to check against those arrays in another while loop. The goal being to improve efficiency and not just run loops, within loops, within loops.
For the most part this works fine. I'm trying to extend the capabilities though and hitting a hurdle.
// query to pull data. / GROUP BY id
// pulls multiple results, but I merely want the results for each distinct ID.
$r = 0;
$u = 0;
$n = 0;
$checkarr=array();
$mustarr=array();
$badarr=array();
$idarr=array();
while ($row = mysql_fetch_array($qry)) {
$check = $row['tbl.check'];
$must = $row['tbl.must'];
$thisid = $row['tbl.id'];
if ($check == 1) {
$checkarr[] = $thisid;
$n++; }
if ($must == 'R') {
$badarr[] = $thisid;
$r++; }
if ($must == 'U') {
$mustarr[] = $thisid;
$u++; }
}
This works to fill the arrays properly with the ID for comparison later. I can just run in_array([id], $checkarr) to see if they match.
What I'm trying to do and failing miserably at... is to fill some sort of associative array so that each $thisid is associated with the final values of $n, $r, and $u. That way, later I can somehow call $thisid['r'] and get the total value of $r associated with that ID.
Something like....
(Pseudo code)
if((in_array($loopid, $mustarr)) {
//display value of $r associated with the $loopid
}
I've tried foreach() loops and just am not figuring it out properly.
How can I associate the total values of $n, $r, and $u with $thisid? Primarily so that I can pull each value outside of this specific loop?
Any tips would be appreciated.
You could make $thisid and your other arrays associative arrays.
$r = 0;
$u = 0;
$n = 0;
$checkarr = array();
$mustarr = array();
$badarr = array();
$idarr = array();
while ($row = mysql_fetch_array($qry)) {
$check = $row['tbl.check'];
$must = $row['tbl.must'];
$thisid = array('id' => $row['tbl.id'], 'n' => $n, 'r' => $r, 'u' => $u);
if ($check == 1) {
$checkarr[$row['tbl.id']] = $thisid; // To make it easier to find $thisid later
$n++; }
if ($must == 'R') {
$badarr[$row['tbl.id']] = $thisid;
$r++; }
if ($must == 'U') {
$mustarr[$row['tbl.id']] = $thisid;
$u++; }
}
If you want to check, if an id is in one of the arrays you could use array_key_exists:
if(array_key_exists($loopid, $mustarr)){
echo $mustarr[$loopid]['r']; // Displaying $r for $loopid
}
if I understand right you can just
if ($must == 'R') {
$badarr[$r] = $thisid;
$r++; }
and you can get value of id by number of iteration
or Vice versa
if ($must == 'R') {
$badarr[$thisid] = $r;
$r++; }
get number of iteration by id

Randomly selecting from previous randomly selected elements from array PHP

First, i created an array of, let`s say, 6 elements. Then i randomly pick 4 elements that are GOOD (on random position i mean).
Now, i want to randomly pick 2 out of those 4 selected that are VERY GOOD.
If the value of array1 is the same with array2, then i want it to say VERY GOOD. Else, say GOOD. If the value is 0, then BAD.
I tried allpossibilities and all failed.
This is my last attempt of doing so...
$array1 = array();
$array2 = array();
while (count($array1) < 4) {
$rand = rand(1,6);
if (!isset($array1[$rand])) {
$array1[$rand] = TRUE;
}
}
while (count($array2) < 2) {
$rand = rand(1,4);
if (!isset($array2[$rand])) {
$array2[$rand] = TRUE;
}
}
$array2 = $array2 + array_fill(1, 4, FALSE);
$array1 = $array1 + array_fill(1, 6, FALSE);
ksort($array1);
ksort($array2);
foreach($array1 as $k => $v){
if ($v != 0)
{echo "GOOD<br>";}
else {echo "BAD<br>";}}
foreach($array2 as $kc => $vc){
if ($v2 !=0)
{echo "VERY GOOD<br>";}
else {echo "BAD<br>";}}
This is what it gives me:
GOOD
GOOD
BAD
GOOD
GOOD
BAD
VERY GOOD
BAD
BAD
VERY GOOD
As you can see, it gave me 4/6 GOODS and then 2/6 VERY GOODS.
What i wanted was 4/6 GOODS and from those 4 selected i want 2/4 VERY GOODS.
How can i do this?
Thanks in advance,
Vlad
You want one array of size 6 so why are you creating multiple? You can either merge them in some fashion or use the first in construction of the second.
But first, I want to point out that the while() loops are very similar, so it should be easy to put that into a function and save some code to write and have a codebase that is better manageable, as you only need to edit one place to have immediate effect instead of many.
Now for the first task, all you need is the $number of elements to be created and the $range. This function will do what one of your while() loops did plus the array_fill(). (demo)
function fillRandom($range, $num = 1) {
$data = array_fill($range[0], $range[1]+1, FALSE);
for ($i=0; $i<$num; $i++) {
do {
$key = mt_rand($range[0], $range[1]);
} while ($data[$key] === TRUE);
$data[$key] = TRUE;
}
return $data;
}
Now comes the more advanced part: In the second run, we can identify 2 out of the 4 TRUE in the array of 6 elements by giving them another $value (as an example).
The $data will be needed in some cases and by using an $anonymous function we can allow the condition for the while() to be passed.
function fillRandom($range, $num = 1, $value = TRUE, $data = array(), $anon = NULL) {
if (empty($data))
$data = array_fill($range[0], $range[1]+1, FALSE);
if ($anon === NULL) {
$anon = function($el) use($value) {
return $el !== $value;
};
}
for ($i=0; $i<$num; $i++) {
do {
$key = mt_rand($range[0], $range[1]);
} while (isSet($data[$key]) && !$anon($data[$key]));
$data[$key] = $value;
}
return $data;
}
You can then do something like this (demo)
$input = fillRandom(array(0, 5), 4);
ksort($input);
print_r($input);
$input = fillRandom(array(0, 5), 2, 2, $input, function($el){
return $el === TRUE;
});
ksort($input);
print_r($input);

PHP: test == return false when he should not

I'm working with symfony2, and i really don't understand what's happen with this.
i have a == test, who don't return true when he should !At the very first iteration of that foreach, the == 's for test answer one time true, but after the first foreach iteration he don't find the other match... I had tried a lot of var_dump, and the var_dump say that: $service->getId() is int(24), and $discountsID is int(24), but the == test isn't true.
So help me, i'm pretty noob with php, and i really don't get what's happen there..
foreach ($services as $service) {
for ($i = 0; $i < count($discountsID); ++$i) {
if ($service->getId() == $discountsID[$i]) { //the fail test..
$bool = $discounts[$i]->getId();
} else {
$bool = -1;
}
}
$view_data['services'][] = array(
'discountId' => bool,
);
}
You may also want to include a condition in your for that terminates the loop where your if condition is reached. Many persons don't like break (neither I do) but this would work:
if( $service->getId() == $discountsID[$i] ){ //the fail test..
$bool = $discounts[$i]->getId();
break;
}
Above the test, add this:
var_dump($service->getId());
var_dump($discountsID[$i]);
die();
And see if the outcome matches
Also this seems wrong to me:
foreach ($services as $service) {
$service->getId()
What does $services consist of?

A way to neaten this PHP code

I have the following PHP code:
<?php
//code above
$pic_1 = $afil['image_1'];
$pic_2 = $afil['image_2'];
$pic_3 = $afil['image_3'];
$pic_4 = $afil['image_4'];
$pic_5 = $afil['image_5'];
$pic_6 = $afil['image_6'];
$pic_7= $afil['image_7'];
$pic_8 = $afil['image_8'];
$pic_9 = $afil['image_9'];
$pic_10 = $afil['image_10'];
if ($pic_1 = "")
{
$pic_1 = //defaultpic - to be defined, same as below
}
if ($pic_2 = "")
{
$pic_2 = //defaultpic
}
?>
Rather than repeat these "if" statements for each picture (up until $pic 10) i just wondered if somebody could point out a more elegant and efficient way of doing it. I am quite new to php and this is a new situation i have encountered. Thanks a lot in advance.
Use arrays and loop through them with just 1 if statement, like this,
foreach($afil as $k => $v) {
if(empty($v))
$afil[$k] = ...//default pic
}
Or, if you are keen to have an additional array $pics (for future use maybe),
foreach($afil as $k => $v) {
$pics[$k] = $v;
if(empty($v))
$pics[$k] = ...//default pic
}
Also, = is an assignment operator. For comparison (or condition check), you need to use == or === (type safe).
Edit:
$afil = mysql_query(...);
while($row = mysql_fetch_array($afil)) {
//In here, say you create an array $result_rows with all the rows
$result_rows[] = $row;
}
Then, use $result_rows in the foreach.
Arrays is your golden solution:
$pic = array('image_1', 'image_2', 'image_3'....);
for ($i = 0; $i < count($pic); $i++){
if ($pic[$i] == ""){
$pic[$i] = //defaultpic -
}
}

Categories