How to compare zero integer with value - php

In database, Student_id is containing 0 value. I want to check it in if condition, but required result is not achieved. I have tried following scenarios in if condition:
if(is_null($item['student_id'])) {}
if($item['student_id'] === 0){}
if($item['student_id'] == 0){}
if(intval($item['student_id']) == 0){}
if(strval("$item['student_id']") == "0"){}
Note: Currently Iam trying to print some message in if conditions. But on student_id = 0, nothing is printed. If student_id is other than 0, then print is working fine.
Can some one guide me what Iam doing wrong and how it can be rectified.
I have added var_dump
array
'_id' =>
object(MongoId)[2]
public '$id' => string '50906d7fa3c412bb040eb577' (length=24)
'student_id' => int 0
'type' => string 'exam' (length=4)
'score' => float 54.653543636265
array
'_id' =>
object(MongoId)[6]
public '$id' => string '50906d7fa3c412bb040eb578' (length=24)
'student_id' => int 0
'type' => string 'quiz' (length=4)
'score' => float 31.950044967421
array
'_id' =>
object(MongoId)[2]
public '$id' => string '50906d7fa3c412bb040eb579' (length=24)
'student_id' => int 0
'type' => string 'homework' (length=8)
'score' => float 14.850457681164

This should work unless your value is not really 0.
if(intval($item['student_id']) == 0){}
Else another way that could work is this, you almost had it:
if($item['student_id'] === '0'){}
But then again, make sure you REALLY have a 0 in there... can you var_dump $item for us just to make sure?

try:
if((int) $item['student_id'] === 0){
....
}

if((int)$item['student_id'] === 0){}

to compare zero by value , first change the retrieved data to integer, then compare using === sign to make sure they are equivalent in both value and type:
if(intval($item['student_id']) === 0){}

Related

Display a condition from an array

Need help guys, below is a var_dump array, I am very noob in php and I am very confused on how to do this, basically all I need is a condition
$fittin_colour_image = get_field('featured_images', get_the_ID());
Above is a code using ACF
var_dump($fittin_colour_image);
below is the result
array (size=2)
0 =>
array (size=3)
'fitting_colour' =>
array (size=1)
0 => string 'Black' (length=5)
'image' => string 'http://localhost/mysite.com/wp-content/uploads/2018/04/image-black.jpg' (length=101)
'image_description' => string '' (length=0)
1 =>
array (size=3)
'fitting_colour' =>
array (size=1)
0 => string 'White' (length=5)
'image' => string 'http://localhost/mysite.com/wp-content/uploads/2018/05/image-white.png' (length=100)
'image_description' => string '' (length=0)
I want to have a condition like this
if this array has a color "Black" then display its image
I am currently using this code
if ($fittin_colour_image[0]['fitting_colour'][0] == 'Black') {
echo $fittin_colour_image[0]['image'];
}
its a bit of a hassle since every time I change the condition I change the [0], sorry but I am confused now, don't know what to say, please help
You're very close. Instead of hard-coding the index (0 in your case) you can, instead, loop over the array and display the image:
foreach ($fittin_colour_image as $image) {
if ($image['fitting_colour'][0] == 'Black') {
echo $image['image'];
}
}
test this
$fittin_colour_image = get_field('featured_images', get_the_ID());
if(!empty($fittin_colour_image)){ // Test if array not empty
foreach ($fittin_colour_image as $image) {
if(!empty($image['fitting_colour'][0]) && $image['fitting_colour'][0] === 'Black'){
echo '<img src="'.$image['image'].'" alt="'.$image['image_description'].'" />';
}
}
}

Why my array is increamenting php laravel 5

I have an array which contains data from the database:
$responses = FormResponses::where('form_id', '>=', $phoneFirstElement->id)->where('form_id', '<=', $phoneLastElement->id)->get();
$responsesArray = $responses->toArray();
Then my nested loop:
foreach ($phone as $key => $value2) // Populate Phone Numbers Horizontally
{
$sheet->cell($start.'9', $value2->phone);
// This will fill the responses for each number
foreach ($metrics as $key => $value)
{
$form_id = $value2->id;
$metrics_id = $value->id;
$neededObjects = array_filter(
$responsesArray,
function ($e) use ($form_id, $metrics_id) {
return $e['form_id'] == $form_id && $e['metrics_id'] == $metrics_id;
}
);
var_dump($neededObjects);
exit;
//$responses = FormResponses::where('form_id', '=', $value2->id)->where('metrics_id', '=', $value->id)->get();
//$sheet->cell($start.$count, $neededObjects[$counter]['response']);
$sheet->cell('C'.$count, $value->question);
$sheet->cell('B'.$count, $value->description);
$sheet->cell('A'.$count, $value->metrics_name);
$counter++;
$count++;
$neededObjects = array();
}
$start++;
$count = 10;
//$counter = 0;
}
My $responsesArray is the data which has lots of record, so I want to extract those data to get the specific one I need using array_filter and storing it in
$neededObjects
However when I make a var_dump I get something like
array (size=1)
0 =>
array (size=7)
'id' => int 141730
'form_id' => int 4430
'metrics_id' => int 1
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
Then when the next records loops in
array (size=1)
1 =>
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
I don't understand why it is increamenting. The first one is 0 then next is 1 . Yes given that I am making an array_filter inside a nested loop but I didn't put any inreament vairables to it and the array filter will aways give me 1 record of data so I am expecting it atleast to be in index 0 or just a format like this:
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
Any results that are returned by array_filter maintain their old keys. If you want the keys to reset then apply array_values to the result.
If you only want one result then call current() or array_pop() on the result to get the first record.
Even if array_filter returns one record, it will still be in the original array with the same key.
array_filter returns the array elements with their keys intact depending upon your filter function. So the keys (0, 1 etc) are the keys in your original array. Use array_pop to get the only element in your array.

Change element of loop

I have an php array like this (var_dump)
I need change one of it's element
array (size=204)
'Address' =>
array (size=3)
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
'CityDistrict' =>
array (size=3)
0 => string 'return $this->hasOne(CityDistrict::className(), ['id' => 'cityDistrictId']);' (length=76)
1 => string 'CityDistrict' (length=12)
2 => boolean false
'Contacts' =>
array (size=3)
0 => string 'return $this->hasMany(Contact::className(), ['addressId' => 'id']);'
1 => string 'Contact' (length=7)
2 => boolean true
'City' =>
array (size=3)
'Addresses' =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'Region' =>
array (size=3)
0 => string 'return $this->hasOne(Region::className(), ['id' => 'regionId']);' (length=64)
1 => string 'Region' (length=6)
2 => boolean false
'CityDistricts' =>
array (size=3)
0 => string 'return $this->hasMany(CityDistrict::className(), ['cityId' => 'id']);'
1 => string 'CityDistrict' (length=12)
2 => boolean true
'CityDistrict' =>
array (size=2)
Addresses =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityDistrictId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
How can i change value 'CityDistrict' in this loop? or 'Addresses'? using php foreach
My code doesn't work please help understand what wrong!
private static function checkExistClass($relations)
{
foreach ($relations as $name => $relation) {
foreach ($relation as $functionName => $functionValue) {
$functionNameGet = 'get' . $functionName;
$directory = new Model;
if (method_exists($directory, $functionNameGet)) {
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
}
}
}
return $relations;
}
I interprete your question that you want to rename the array index Addresses to NewAddresses:
$relations['CityDistrict']['NewAddresses'] = $relations['CityDistrict']['Addresses'];
unset($relations['CityDistrict']['Addresses']);
EDIT:
to do that in your foreach loop, change:
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
to:
$relations[$name]['funky_key_'.$functionName] = $functionValue;
unset($relations[$name][$functionName]);
maybe this is what you're looking
if (isset($array['n'])) {
$array['name'] = $array['n'];
unset($array['n']);
}
you can see the complete post in Change key in associative array in PHP
see you!
PD Sorry, for my english is not the best
Your loop seems wrong. In the outer loop, $name assumes values such as 'Address', and $relation is an array such as { 'City' => ..., 'CityDistrict' => ... }.
So in the second loop $functionName assumes values such as City, CityDistrict and Contacts.
If you want to change that, you need to do something like #hellcode suggested:
if ('CityDistrict' == $functionName) {
$relations[$name]['NewDistrict'] = $relations[$name][$functionName];
unset($relations[$name][$functionName]);
continue;
}
This looks like a Laravel/Eloquent problem to me. If you can state more precisely what it is that you're trying to accomplish, possibly someone could be of more use.
Also, you seem to want to create a function given its code in a string. To do this you would need create_function (or declare the function as anonymous/lambda function):
$code = "return 42;";
$array['function'] = create_function('', $code);
print $array['function']();
Note that the use of create_function is somewhat deprecated. Also you need a PHP > 5.3+ (or 5.4+ if you go lambda and require $this).

PHP: IF sentence is run, but dumps says it shouldn't

im sitting with a pretty simple image uploader, where the first image uploaded is going to be treated in a special manner. I then run a loop over all the files, and skip the first image.
For this i have named the first image headImage, and i skip it when it has been moved, and done the other stuff to it.
I have cut out all excess code, and are only displaying the loop causing my problem:
Sorted image array:
array (size=5)
'headImage' =>
array (size=5)
'name' => string '8-skilling-1606-eller-07-54-1-h93a.jpg' (length=38)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/phpNUoAtX' (length=14)
'error' => int 0
'size' => int 37748
0 =>
array (size=5)
'name' => string '807003718_2_Big.jpg' (length=19)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/php1TXBdm' (length=14)
'error' => int 0
'size' => int 36328
Foreach loop which skips if the fileKey is "headImage", and dumps the fileKey
foreach($uploadFiles as $fileKey => $file){
if($fileKey == "headImage"){
var_dump($fileKey);
continue;
}
}
And the output from var_dump:
string 'headImage' (length=9)
int 0
Now, why is the if sentence ran when the value of $fileKey clearly isn't "headImage"?
Because "string" == 0 in PHP.
You have to compare using type too, try === comparison:
foreach($uploadFiles as $fileKey => $file){
if($fileKey === "headImage"){
var_dump($fileKey);
continue;
}
}
best and safe way to compare two string is using php strcmp function
use like this :
foreach($uploadFiles as $fileKey => $file){
if(strcmp($fileKey ,"headImage") == 0){
var_dump($fileKey);
continue;
}
}
PHP strcmp function Document

php json_decode return [object Object]

I have a problem with JSON data in PHP. I need to use data from this JSON in my SQL statement. When I'm trying to debug it with echo(var_dump, or print_r is not working too) command the output with is
{"records":"tekst","name":"[object Object]"}
This is a JSON structre:
{
records: 'tekst',
name: {
imie: 'imie1',
nazwisko: 'nazwisko1'
}
}
I'm trying to decode this by json_decode(), but I have an error
"Warning: json_decode() expects parameter 1 to be string, array
given".
Does anyone know what's wrong?
PHP manual about JSON and the format required: function.json-decode. basically, double quotes only and names must be quoted.
a demonstration of conversion using PHP.
So, you supply the json string that looks like, with the whitespace removed, like this:
{records:[{id:1,name:'n1'},{id:2,name:'n2'}]}
Which is an object containing an array with two entries that could be arrays or objects.
Except, it is not a valid JSON string as it contains single quotes. And PHP wants all the names in double quotes, as in "id":1.
So, possible PHP code to recreate that, assuming arrays as the inner entries is:
$json = new stdClass();
$records = array();
$entry = array('id' => 1, 'name' => 'n1');
$records[] = $entry;
$entry = array('id' => 2, 'name' => 'n2');
$records[] = $entry;
$json->records = $records;
$jsonEncoded = json_encode($json);
Which, when 'dump'ed looks like:
object(stdClass)[1]
public 'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
Now, the string that structure produces is:
{"records":[{"id":1,"name":"n1"},{"id":2,"name":"n2"}]}
Which looks similar to yours but is not quite the same. Note the names in double quotes.
However, if your json string looked the same then PHP could decode it, as is shown below:
$jsonDecoded = json_decode($jsonEncoded);
var_dump($jsonDecoded, 'decoded');
Output: Note all objects...
object(stdClass)[2]
public 'records' =>
array
0 =>
object(stdClass)[3]
public 'id' => int 1
public 'name' => string 'n1' (length=2)
1 =>
object(stdClass)[4]
public 'id' => int 2
public 'name' => string 'n2' (length=2)
We may want arrays instead so use the true as the second parameter in the 'decode'
$jsonDecoded = json_decode($jsonEncoded, true);
var_dump($jsonDecoded, 'decoded with true switch');
Output: with arrays rather than objects.
array
'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
string 'decoded with true switch' (length=24)

Categories