PHP output number with leading zeros incorrectly - php

I have a line in a file like this:
0000000/BirthstoneEnsemble/f/0/1380152724
I explode by $pieces = explode("/", $line);
when I do echo $pieces[0] == "0000000" it returns false. I try to cast pieces[0] to string, but it is always incorrect.
function build_file_assoc() {
global $dir;
$assoc = [];
$file_assoc = file($dir . 'rsnjxdlxwxwun.dbt');
for($i = 0; $i < count($file_assoc) - 1; $i++) {
if($i > 0) {
list($parent_folder, $image_name, $tag, $size, $date) = explode("/", $file_assoc[$i]);
$assoc[] = [
'parent_folder' => (string)$parent_folder,
'image_name' => $image_name,
'tag' => $tag,
'size' => $size,
'date' => $date
];
}
}
return $assoc;
}
$g = build_file_assoc();
$first = $g[0]['parent_folder'];
echo $first == "0000000"; // false
file contents:
0000000/BirthstoneEnsemble/f/0/1380152724
0000000/Thumbs.db/a/83968/1384248954
0000000/bridal images for frame/f/0/1380152879

Try print array print_r($pieces) and you will see what is saved in specific fields after exlode.

If I run the code from your question, it works:
<?php
$line = '0000000/BirthstoneEnsemble/f/0/1380152724';
$pieces = explode("/", $line);
echo var_dump($pieces[0] == "0000000"); //true
?>

I would use the identical comparison operator and type cast pieces[0] as a string.
$line = '0000000/BirthstoneEnsemble/f/0/1380152724';
$pieces = explode('/',$line);
//echo '<pre>',print_r($pieces),'</pre>';
if((string)$pieces[0]==='0000000'){
echo true;
}else{
echo false;
}
// output: 1

var_dump
Check the actual value of your piece, since it's possible that you have a space or a tab character in there - var_dump will show it for you.
similar issue
Take a look at this post.

Related

How to count and print characters that occur at least Y times?

I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.
Example :
Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
This what I could achieve so far:
$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
So, it is very short version
function check($string,$count = 1) {
$achives = [];
$strArray = count_chars($string, 1);
array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
$cnt!==$count?:$achives[chr($letter)] = $cnt;
});
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));
But it is exactly answer for your question:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = str_split($string, 1);
foreach($strArray as $index => $char ){
$strings[$char] = isset($strings[$char])?++$strings[$char]:1;
}
if($count) {
foreach($strings as $char => $cnt) {
if($cnt==$count) {
$achives[$char] = $cnt;
}
}
}
return $achives;
}
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
You can simply do this with php str_split() and array_count_values() built in functions. i.e.
$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
foreach ($letterCountArray as $key => $value) {
echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}
Output

Multiple String Replace Based on Index

I need to replace multiple sections of a string based on their indices.
$string = '01234567890123456789';
$replacements = array(
array(3, 2, 'test'),
array(8, 2, 'haha')
);
$expected_result = '012test567haha0123456789';
Indices in $replacements are expected not to have overlaps.
I have been trying to write my own solution, split the original array into multiple pieces based on sections which needs to be replaced or not, and finally combine them:
echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'
function str_replace_with_indices ($string, $replacements) {
$string_chars = str_split($string);
$string_sections = array();
$replacing = false;
$section = 0;
foreach($string_chars as $char_idx => $char) {
if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
$replacing = !$replacing;
$section++;
}
$string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
$string_sections[$section]['original'] .= $char;
if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
}
$string_result = '';
foreach($string_sections as $s) {
$string_result .= ($s['new']) ? $s['new'] : $s['original'];
}
return $string_result;
}
function replacing($replacements, $idx) {
foreach($replacements as $r_idx => $r) {
if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
return $r_idx;
}
}
return false;
}
Is there any more effective way to achieve the same result?
The above solution doesn't look elegant and feels quite long for string replacement.
Use this
$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
$index = $s[0]+$index_strlen;
$str = substr_replace($str, $s[2], $index, $s[1]);
$index_strlen += strlen($s[2]) - $s[1];
}
echo $str;

PHP - CSV to table not converting as expected

I am trying to create SQL INSERT statements from a CSV file. I have successfully opened and read the file. I have even output the file in a table format. However, the alterations I do in the for loop such as when $c == 0 do not work. It just outputs to the table exactly as it was in the csv file. That is what I am trying to change! To keep with that example, I am trying to make the name "John Doe" be "john" and "Doe". The CSV file has the names as one and I'd like to split into first and last.
Also, the phone numbers aren't changing either. The code to change them begins with $c == 5. The funny thing is when I put them into here: http://ideone.com/HfGXJk It works fine.
<?php
fgetcsv_PHP();
function fgetcsv_PHP()
{
if (($handle = fopen("guests.csv", "r")) !== FALSE)
{
$length = 1000;
$delimiter = ",";
$fname = array();
$lname = array();
$address = array();
$city = array();
$state = array();
$zip = array();
$phone = array();
$email = array();
//print opening table
echo "<table border='1'>\n";
while ( ( $data = fgetcsv( $handle, $length, $delimiter ) ) !== FALSE )
{
// Count number of array elements in $data
$num = count($data);
// Print opening table row HTML tag
echo "<tr>\n";
//loop through array
for ($c=0; $c < $num; $c++)
{
if ($c == 0)
{
$name = $c;
$name = explode(" ",$name);
$first = array_shift($name);
$last = array_pop($name);
array_push($fname, $first);
array_push($lname, $last);
echo "<td>".$data[$first]."</td>\n";
}
if ($c == 1)
{
array_push($address, $c);
echo "<td>".$data[$c]."</td>\n";
}
if ($c == 2)
{
array_push($city, $c);
echo "<td>".$data[$c]."</td>\n";
}
if ($c == 3)
{
array_push($state, $c);
echo "<td>".$data[$c]."</td>\n";
}
if ($c == 4)
{
array_push($zip, $c);
echo "<td>".$data[$c]."</td>\n";
}
if ($c ==5)
{
$phnum = $c;
$phnum = preg_replace('~[^0-9]~','',$phnum);
array_push($phone, $phnum);
echo "<td>".$data[$phnum]."</td>\n";
}
if ($c == 6)
{
array_push($email, $c);
echo "<td>".$data[$c]."</td>\n";
}
}
// Print closing table row HTML tag
echo "</tr>\n";
}
// Print close table HTML tag
echo "</table>";
// Close the file pointed to by $handle
fclose($handle);
}
}
?>
The part reading the name, sets $name to 0, explodes it at the non existing space, puts the 0 from the first element of the array (from the explode) in $first and outputs $data[$first] meaning $data[0] - the original value.
Refactored to PHP 5.5:
$file = new SplFileObject('guests.csv', 'r');
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(',', '"');
$converter = function($traversable) {
foreach ($traversable as $data) {
list($first, $last) = explode(' ', $data[0]);
$address = $data[1];
$city = $data[2];
$state = $data[3];
$zip = $data[4];
$phone = preg_replace('([^\d])', '', $data[5]);
$email = $data[6];
$result = array(
'first' => $first,
'last' => $last,
'address' => $address,
'city' => $city,
'state' => $state,
'zip' => $zip,
'phone' => $phone,
'email' => $email,
);
yield $result;
}
};
foreach ($converter($file) as $data) {
var_dump($data);
}
The code you posted to the other site is not the code you posted here. If that works, fine. It has little to do with this:
if ($c ==5)
{
$phnum = $c;
$phnum = preg_replace('~[^0-9]~','',$phnum);
array_push($phone, $phnum);
echo "<td>".$data[$phnum]."</td>\n";
}
Look at $phnum. The first thing you do is set it to $c, i.e 5. Then you remove all the non-numeric characters in 5, push the result onto an array which you don't appear to use, and output $data[$phnum], i.e. $data[5], your original data.

How can i explode the string with , and |

How can i explode this? mars#email.com,123,12,1|art#hur.com,321,32,2
the output should be :
$email = mars#email.com
$score = 123
$street = 12
$rank = 1
then remove the |
$email = art#hur.com
$score = 321
$street = 32
$rank = 2
$string = mars#email.com,123,12,1|art#hur.com,321,32,2
explode( ',', $string );
is that correct?
foreach(explode('|', $str) as $v){
$data = explode(',',$v);
echo '$email = '.$data[0].
'$score = '.$data[1].
'$street = '.$data[2].
'$rank = '.$data[3];
}
You might want to use strtok() rather than explode().
http://www.php.net/manual/en/function.strtok.php
$arr = preg_split( '"[,|]"', 'mars#email.com,123,12,1|art#hur.com,321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
$email = $arr[$i];
$score = $arr[$i+1];
$street = $arr[$i+2];
$rank = $arr[$i+3];
}
you need to store the new array in variable >
$arr = explode(',',$string);
and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];
You need to unravel it in the right order:
first the blocks separated by |
then individual cells separated by ,
A concise way to do so is:
$array = array_map("str_getcsv", explode("|", $data));
Will give you a 2D array.
Use strtok and explode.
$tok = strtok($string, "|");
while ($tok !== false) {
list($email, $score, $street, $rank) = explode(',', $tok);
$tok = strtok(",");
}
I think what you want is something like this
$output = array();
foreach (explode('|', $string) as $person) {
$output[] = array(
'email' => $person[0],
'score' => $person[1],
'street' => $person[2],
'rank' => $person[3]
)
}
This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use
echo $output[0]['email']; // mars#email.com
and to access person 2's street, you'd use
echo $output[1]['street']; // 32

how to explode a string and make an echo of a chosen attribute

I have a string containing ; subdivided by , and would like to make an echo of a chosen value.
My string is $string='Width,10;Height,5;Size,1,2,3'
I want to make an echo of the Height value (echo result must be 5)
$parts = explode(';', $string);
$component = explode(',', $parts[1]); // [1] is the Height,5 portion
echo $component[1]; // 5
Or this:
$p = explode(';', $string);
$data = array();
foreach($p as $part) {
$split = explode(',',$part,2); //the 'Size' bit different that the rest. I assume 1,2,3 is the value for Size?
$data[$split[0]] = $split[1];
}
$what_you_want_to_find = 'Height';
echo $data[$what_you_want_to_find];
try this:
$attrs = explode(";", $string);
$attrHeight = "";
foreach ($attrs as $value) {
if (strpos($value, "Height") !== false)
$attrHeight = explode(",", $value);
}
echo $attrHeight;

Categories