nl2br converts true to int and false to empty string - php

I am using PHP Version 5.6.25. The following code is all that's needed to replicate the issue.
$data['foo'] = true;
$data['bar'] = false;
var_dump($data);
$data['foo'] = nl2br($data['foo']);
$data['bar'] = nl2br($data['bar']);
array_walk_recursive($data, "filter");
var_dump($data);
This gives the following result.
array (size=2)
'foo' => boolean true
'bar' => boolean false
array (size=2)
'foo' => string '1' (length=1)
'bar' => string '' (length=0)
Is this a PHP bug? Is there a workaround?

from the manual nl2br
string nl2br ( string $string [, bool $is_xhtml = true ] )
nl2br expects a string as an input, casting a boolean to a string returns 1 for true and "" for false; so no surprises that's what you get in this case.
In your filter function you can check the variable type before deciding how to filter it.

Related

Extract just the strings from an array_column array return

I've got told many times, if there is a new question even on the same code to just create a new thread so here I am. Thanks to the guys for helping me with the previous question.
I have the following code:
/* Return an array of _octopus_ids */
$offices = array_map(
function($post) {
return array(
'id' => get_post_meta($post->ID, '_octopus_id', true),
);
},
$query->posts
);
/* Dump out all the multi-dimensional arrays */
var_dump($offices);
$test = array_column($offices, 'id');
var_dump($test);
var_dump($offices) dumps the following:
array (size=10)
0 =>
array (size=1)
'id' => string '1382' (length=4)
1 =>
array (size=1)
'id' => string '1330' (length=4)
var_dump($test) dumps the following:
array (size=10)
0 => string '1382' (length=4)
1 => string '1330' (length=4)
Problem:
How can I use the following code:
$results = $octopus->get_all('employees/' . $test; which results in an Notice: Array to string conversion error.
I want to be able to make a results call such as this $results = $octopus->get_all('employees/1382'); - So I want just the numeric string of $test to be appended to the end of employees/
If I hardcode the 1382 after employees/, I get the following result:
object(stdClass)[1325]
public 'id' => int 1382
What's the proper way to array of strings into just strings?

why it returns empty value but of boolean type when no match is found

I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?
$arr =Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush'
),
1 => Array
(
'uid' => '5465',
'name' => 'Stefanie Mcmohn'
),
2 => Array
(
'uid' => '40489',
'name' => 'Michael'
)
);
$match = array_search('546',array_column($arr, 'uid'));
echo gettype($match);
If you take a look at array_search method description http://php.net/manual/ro/function.array-search.php it says: Returns the key for needle if it is found in the array, FALSE otherwise. There is your answer.
http://php.net/manual/en/function.array-search.php
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource and NAN).
array_search() function returns the key for needle if it is found in the array, FALSE otherwise. So when you are using gettype() on the return value, then it will return the type of FALSE i.e. BOOLEAN for unsuccessful search, otherwise INT index value.
your code is working , when array_search not found then return false and if gettype($match); then show boolean and if found then return index so in this case return integer
this is code which return
<?php
$arr =Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush'
),
1 => Array
(
'uid' => '5465',
'name' => 'Stefanie Mcmohn'
),
2 => Array
(
'uid' => '40489',
'name' => 'Michael'
)
);
$match = array_search('5465',array_column($arr, 'uid'));
echo gettype($match);
and output is: integer
this is normal example
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
for more information
http://php.net/manual/ro/function.array-search.php
array_search() returns FALSE when it cannot find the needle in the haystack.
The comparison is done using ==. This means, the values are converted to the same type, if needed. But their values must be the same after conversion. It doesn't match substrings.
echo(FALSE); doesn't print anything. The type of FALSE is boolean, indeed. And FALSE is == with the empty string (''), zero (0), the string that contain the number zero ('0') and other empty values.

PHP - Convert foreach to arrays

Anyone can help me
I have a little problem with the following code
foreach ($products as $product) {
$product->name;
$product->code;
...
}
My output code with var_dump($products)
array
0 =>
object(stdClass)
...
...
...
1 =>
object(stdClass)
...
...
...
And I need output something like this
$output = array(
array('name' => 'item1', 'code' => 'code1', 'price' => '10.00'),
array('name' => 'item2', 'code' => 'code2', 'price' => '20.00')
);
For this purpose, there is a function is php json_decode()
mixed json_decode ( string $json [, bool $assoc = false [, int $depth
= 512 [, int $options = 0 ]]] )
Need to use this function sensibly.
As you see in the function description,
The function's three parameters:
1) Variable to be converted.
2) Return as associative array.
3) Depth: default => 512. Means upto depth of 512 levels (in case of multi-dimensional array or complex object), the child elements will be converted into arrays if second parameter is set to true.
First encode your variable by json_encode() and the decode it with using
json_decode().
json_decode() 's second parameter should be set to true.
This true means return associative array instead of original type.
Pseudo code:
$output = json_decode(json_encode($yourVar), TRUE);

Import information from file to mysql with php

How can i import information from a file (like below) to my mysql database by a php file?
I was thinking by open a file, insert a row into a variabele and check every line for an = mark and insert the information into array's by checking the tag bevore the =.
Is this the right way or are there better ways.
Example file:
# Disc length: 926 seconds
# Revision: 0
# Processed by: cddbd v1.5PL3 Copyright (c) Steve Scherf et al.
# Submitted via: audiograbber 1.83.01
DISCID=00039c14
DTITLE=3M Littmann Stethoscope Edition / 20 Beispiele zur Herz- und Lungenausku
DTITLE=ltation
DYEAR=1997
DGENRE=Medizin
TTITLE0=Normale Herztöne
TTITLE1=Dritter Herzton (physiologisch)
TTITLE2=Vierter Herzton
TTITLE3=Aortenklappenstenose
TTITLE4=Mitralklappeninsuffizienz
TTITLE5=Mittelsystolischer Klick
TTITLE6=Ventrikelseptum-Defekt
TTITLE7=Atriumseptum-Defekt
TTITLE8=Mitralklappenstenose
TTITLE9=Aortenklappeninsuffizienz
TTITLE10=normales tracheales Atemgeräusch
TTITLE11=normales vesikuläres Atemgeräusch
TTITLE12=feine Krepitation mit leichter bronchialer Atmung
TTITLE13=rauhe Krepitation
TTITLE14=bronchiale Atmung
TTITLE15=Stridor beim Einatmen
TTITLE16=Rhonchus
TTITLE17=pfeifender Rhonchus (Keuchatmen)
TTITLE18=feine Krepitation (Knisterrasseln)
TTITLE19=pleurales Reibungsgeräusch
EXTD=
EXTT0=
EXTT1=
EXTT2=
EXTT3=
EXTT4=
EXTT5=
EXTT6=
EXTT7=
EXTT8=
EXTT9=
EXTT10=
EXTT11=
EXTT12=
EXTT13=
EXTT14=
EXTT15=
EXTT16=
EXTT17=
EXTT18=
EXTT19=
PLAYORDER=
Try this:
$settingArray = array();
$text = file('file.txt');
foreach($text as $line){
$line = str_replace(array("\r", "\n"), '', $line);
if(substr($line, 0, 1) != '#' && !empty($line)){
$key = substr($line, 0, strpos($line, "="));
$value = substr($line, strpos($line, "=") + 1);
$value = substr($value, 0, strpos($value, "#") != 0 ? strpos($value, "#") : strlen($value)); //removes everything behind a # sign
$settingArray[$key] = $value;
}
}
var_dump($settingArray);
/*this will print:
array (size=46)
'DISCID' => string '00039c14' (length=8)
'DTITLE' => string 'ltation' (length=7)
'DYEAR' => string '1997' (length=4)
'DGENRE' => string 'Medizin' (length=7)
'TTITLE0' => string 'Normale Herztöne ' (length=17)
'TTITLE1' => string 'Dritter Herzton (physiologisch)' (length=31)
'TTITLE2' => string 'Vierter Herzton' (length=15)
'TTITLE3' => string 'Aortenklappenstenose' (length=20)
'TTITLE4' => string 'Mitralklappeninsuffizienz' (length=25)
'TTITLE5' => string 'Mittelsystolischer Klick' (length=24)
'TTITLE6' => string 'Ventrikelseptum-Defekt' (length=22)
'TTITLE7' => string 'Atriumseptum-Defekt' (length=19)
'TTITLE8' => string 'Mitralklappenstenose' (length=20)
'TTITLE9' => string 'Aortenklappeninsuffizienz' (length=25)
'TTITLE10' => string 'normales tracheales Atemgeräusch' (length=32)
'TTITLE11' => string 'normales vesikuläres Atemgeräusch' (length=33)
'TTITLE12' => string 'feine Krepitation mit leichter bronchialer Atmung' (length=49)
'TTITLE13' => string 'rauhe Krepitation' (length=17)
'TTITLE14' => string 'bronchiale Atmung' (length=17)
'TTITLE15' => string 'Stridor beim Einatmen' (length=21)
'TTITLE16' => string 'Rhonchus' (length=8)
'TTITLE17' => string 'pfeifender Rhonchus (Keuchatmen)' (length=32)
'TTITLE18' => string 'feine Krepitation (Knisterrasseln)' (length=34)
'TTITLE19' => string 'pleurales Reibungsgeräusch' (length=26)
'EXTD' => boolean false
'EXTT0' => boolean false
'EXTT1' => boolean false
'EXTT2' => boolean false
'EXTT3' => boolean false
'EXTT4' => boolean false
'EXTT5' => boolean false
'EXTT6' => boolean false
'EXTT7' => boolean false
'EXTT8' => boolean false
'EXTT9' => boolean false
'EXTT10' => boolean false
'EXTT11' => boolean false
'EXTT12' => boolean false
'EXTT13' => boolean false
'EXTT14' => boolean false
'EXTT15' => boolean false
'EXTT16' => boolean false
'EXTT17' => boolean false
'EXTT18' => boolean false
'EXTT19' => boolean false
'PLAYORDER' => boolean false*/
You should simple ignore lines starting with # and then in all other lines (not-empty) find first occurrence of = sign and using susbtr (or mb_substr) you will get columns and columns values.
EDIT
Someone suggest it's INI file however in fact it isn't so you cannot use parse_ini_file function. First thing is that comments here start with '#` what would generate Deprecated warning (ini PHP 5.5.12) and in addition because no quotes were used you will get warning :
Warning: syntax error, unexpected '(' in test.ini on line 12
and this function will return false
EDIT2
I would do it this way:
<?php
$data = array();
$lines = file('test.ini');
mb_internal_encoding('UTF-8');
foreach($lines as $line){
$line = trim($line);
if ($line == '' || mb_substr($line,0,1) == '#') {
continue;
}
$pos = mb_strpos($line, '=');
if ($pos == false) { // == not ===
continue;
}
$data[mb_substr($line,0,$pos)] = mb_substr($line, $pos + 1);
}
var_dump($data);
You need to trim each line first and remove empty lines and lines starting with # as I said before, then you check for occurrence of =. If it's not found or at 0 position simple you need to ignore this line, all other lines are placed into $data array

Getting Blank instead of a value when using -> in PHP

I am making a web app. In one part of it, I have JS send a JSON string to PHP. The conent of the string is:
{"date":"24-03-2014","Cars":["Cheap","Expensive"]}
I want to convert the string into an object, for which I am doing:
$meta = $_POST["meta"];
$obj = json_decode($meta);
echo $obj->date;
Anyhow, Instead of having 24-03-2014 as the output, I am getting a blank line as the output.
What's wrong? What's the correct way of doing this?
Not able to re-produce it:
$jsonStr = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$jsonObj = json_decode($jsonStr);
var_dump($jsonObj);
var_dump($jsonObj->date);
Outputs:
object(stdClass)[1]
public 'date' => string '24-03-2014' (length=10)
public 'Cars' =>
array (size=2)
0 => string 'Cheap' (length=5)
1 => string 'Expensive' (length=9)
string '24-03-2014' (length=10)
Are you sure your $_POST['meta'] is set & has values?
Below works like a charm. Your $_POST["date"] has not correct value inside. Try var_dump($_POST) to debug it.
<?php
$input = '{"date":"24-03-2014","Cars":["Cheap","Expensive"]}';
$meta = $input;
$obj = json_decode($meta);
var_dump($obj->date); //Prints string(10) "24-03-2014"
?>

Categories