Array not return properly - php

Following code:
$names = file_get_contents('names.txt');
var_dump($names);
Is returning in var_dump:
array (size=1)
0 => string 'asd
dwqd
asfa
fewfw' (length=22)
Meanwhile, this returns correct way:
$test = array('tete','asdasd','yryr');
var_dump($test);
Result:
array (size=3)
0 => string 'tete' (length=4)
1 => string 'asdasd' (length=6)
2 => string 'yryr' (length=4)
So, the code block when I try to get names from file and make an array of them return an wrong format array. names.txt is built as following:
asd
dwqd
asfa
fewfw

Your problem is you're not splitting the lines into an array, it's just reading the whole files as a block of text.
Use file() with the FILE_IGNORE_NEW_LINES flag. The flag says Do not add newline at the end of each array element, turning your multiple lines into single lines of an array.
Try:
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
var_dump($names);

You are just printing normal string from text file. You need to explode in to array.
Use,
$array = explode(" ",$names);
var_dump($array);

Use file():
$names = trim(file('names.txt'));
var_dump($names);

Related

Explode string with two different separators to create multidimensional array

I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));

Convert a PHP string array into an Array object

I'm developing a PHP app and I have a problem by converting a string array into an object array. I tried to force casting my string into an array by using (array), but it won't works. Here is my string (debug):
string '['method'=>'post','action'=>'#']' (length=32)
As you can see, it's a perfect array into a string and i want to convert that string.
My question is simple, does PHP has a function to convert directly a string into an array (I think no) or i have to convert my string by using explode?
From php 5.4 you can simply eval:
eval("\$f=['method'=>'post','action'=>'#'];");
var_dump($f);
For olders you have to fix the string a bit, change the 1st "[" to "array(" and the last "]" to ")".
The question is a bit duplicate of How to create an array from output of var_dump in PHP?
Here is how you define an array.
But before writing code, please take a look at manuels
$arrayName = array('method' => 'post', 'action' => '#');
The output will read
array (size=2)
'method' => string 'post' (length=4)
'action' => string '#' (length=1)
You can use preg_split and foreach() to make this work:
$str = "['method'=>'post','action'=>'#']";
$splitArray = preg_split("/[,']+/", $str);
foreach ($splitArray as $k => $val) {
if ($val == '=>') {
$newArr[$splitArray[$k - 1]] = $splitArray[$k + 1];
}
}
var_dump($newArr);
/*newArr
Array
(
[method] => post
[action] => #
)*/

PHP array_search preg

I want to search for '01.' that begins with the number of the array.
Expected output:
1 => string '01.02' (length=5)
2 => string '01.03' (length=5)
3 => string '01.04' (length=5)
32 => string '02.02' (length=5)
33 => string '02.03' (length=5)
34 => string '02.04' (length=5)
35 => string '02.05' (length=5)
My code:
$key = array_search('/^01./', $tomb_datum);
echo $key;
var_dump($key);
These preg match not work.
There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.
See the below example: FIDDLE
$haystack = array (
'01.02',
'01.03',
'02.05',
'02.07'
);
$matches = preg_grep ('/^01/i', $haystack);
print_r ($matches);
If you're looking to filter the array, use array_filter:
$resultArray = array_filter($array, function($elm) {
if (preg_match('/^01/', $elm)) {
return true;
}
return false;
});
Hope this helps.
You could use T-Regx library which allows for all sorts of array filters:
pattern('^01.')->forArray($tomb_datum)->filter()
You can also use other methods like:
filter() - for regular (sequential) arrays
filterAssoc() - for associative arrays (filterAssoc() preserves keys)
filterByKeys() - to filter an array by keys, not values
PS: Notice that with T-Regx you don't need /.?/ delimiters!

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"
?>

how to find "http" in string from array?

In PHP I have an array like this:
array
0 => string 'open' (length=4)
1 => string 'http://www.google.com' (length=21)
2 => string 'blank' (length=5)
but it could also be like:
array
0 => string 'blank' (length=5)
1 => string 'open' (length=4)
2 => string 'http://www.google.com' (length=21)
now it is easy to find "blank" with in_array("blank", $array) but how can I see if one string is starting with "http"?
I've tried with
array_search('http', $array); // not working
array_search('http://www.google.com', $array); // is working
now everything after `http? could vary (how to write vary, varie? could be different is what I mean!)
Now do I need a regex or how can I check if http exists in array string?
Thanks for advices
"Welcome to PHP, there's a function for that."
Try preg_grep
preg_grep("/^http\b/i",$array);
Regex explained:
/^http\b/i
^\ / ^ `- Case insensitive match
| \/ `--- Boundary character
| `------ Literal match of http
`--------- Start of string
Try using the preg_grep function which returns an array of entries that match the pattern.
$array = array("open", "http://www.google.com", "blank");
$search = preg_grep('/http/', $array);
print_r($search);
Solution without regex:
$input = array('open', 'http://www.google.com', 'blank');
$output = array_filter($input, function($item){
return strpos($item, 'http') === 0;
});
Output:
array (size=1)
1 => string 'http://www.google.com' (length=21)
You can use preg_grep
$match = preg_grep("/http/",$array);
if(!empty($match)) echo "http exist in the array of string.";
or you can use foreach and preg_match
foreach($array as $check) {
if (preg_match("/http/", $check))
echo "http exist in the array of string.";
}

Categories