PHP - How to echo a value from mapped Array? - php

I have a mapped Array named: $mapped
Below is a result of var_dump($mapped);
array(32) {
["Age: "]=> string(137) "21 Years. "
["Ethnicity: "]=> string(122) "Caucasian "
["Location: "]=> string(152) "Paris, France "
}
The problem is I don't get any results with: echo $mapped["Age: "];
I have tried:
echo $mapped["Age: "]; // No results
echo $mapped["Age:"]; // No results
echo $mapped[" Age: "]; // No results
echo $mapped['Age: ']; // No results
echo $mapped['Age:']; // No results
var_dump($mapped["Age: "]); // result: NULL
What am I doing wrong? I want echo $mapped["Age: "]; to result: 21 Years
Thank you for your help

Cybrog, white spaces are creating problem for you. Try the code below to remove the white space and access any element without any extra effort.
$keys = str_replace( ' ', '', array_keys($mapped) );
$values = array_values($mapped);
$mapped = array_combine($keys, $values);
var_dump($mapped);
try this one to remove html
$keys = array_map("trim", array_map("strip_tags", array_keys($mapped)));
$values = array_map("trim", array_map("strip_tags", array_values($mapped)));
$mapped = array_combine($keys, $values);
var_dump($mapped);

Related

How to output repeat strings with looping and explode method only

e.g. "I think I got a long way to go to market."
In this case, I want to output
I 2
think 1
got 1
a 1
long 1
way 1
to 2
go 1
market 1
Code:
<?php
$tmp = explode (" ", $text);
echo "
My Words
Repetition
";
foreach ($tmp as $a)
{
echo "" $a."" ;
echo "" ;
}
echo ""
?>
You can try with
$text = "I think I got a long way to go to market.";
$tmp = explode (" ", $text);
foreach($tmp as $a){
$result[$a] += 1;
}
foreach($result as $value => $occurrences){
echo "$value $occurrences\n";
}

How remove the last comma in my string?

I've been trying to figgure out using substr, rtrim and it keeps removing all the commas. And if it doesn't nothing shows up. So I am basicly stuck and require some help.. Would've been apriciated.
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
I am guessing that you are trying to take an array of strings of space separated ids and flatten it into a comma separated list of the ids.
If that is correct you can do it as:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
output:
abc, def, ghi, jklm, nopq, rstu, vwxy
Change ltrim by rtrim:
ltrim — Strip whitespace (or other characters) from the beginning of a string
rtrim — Strip whitespace (or other characters) from the end of a string
<?php
$ids = Array ( 1,2,3,4 );
$final = '';
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$final .= $value . ', ';
}
}
echo rtrim($final, ', ') . '<br>';
echo substr($final, 0, -2) . '<br>'; //other solution
}
?>
If your array looks like;
[0] => 1,
[1] => 2,
[2] => 3,
...
The following should suffice (not the most optimal solution);
$string = ''; // Create a variable to store our future string.
$iterator = 0; // We will need to keep track of the current array item we are on.
if ( is_array( $ids ) )
{
$array_length = count( $ids ); // Store the value of the arrays length
foreach ( $ids as $id ) // Loop through the array
{
$string .= $id; // Concat the current item with our string
if ( $iterator >= $array_length ) // If our iterator variable is equal to or larger than the max value of our array then break the loop.
break;
$string .= ", "; // Append the comma after our current item.
$iterator++; // Increment our iterator variable
}
}
echo $string; // Outputs "1, 2, 3..."
Use trim() function.
Well, if you have a string like this
$str="foo, bar, foobar,";
use this code to remove the Last comma
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
output: foo, bar, foobar

Get VALUES from url in PHP

I need to get ID´s from url:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32
If i use $_GET['ID'] a still get only last ID value. I need to get all of them to array, or select.
Can anybody help me?
Use array syntax:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
var_dump($_GET['ID']);
array(4) {
[0]=>
int(1)
[1]=>
int(5)
[2]=>
int(24)
[3]=>
int(32)
}
}
echo $_GET['ID'][2]; // 24
The format in the URL is wrong. The second "ID" is overwriting the first "ID".. use an array:
http://www.example.org/?id[]=1&id[]=2&id[]=3
In PHP:
echo $_GET['id'][0]; // 1
echo $_GET['id'][1]; // 2
echo $_GET['id'][2]; // 3
To get this you need to make ID as array and pass it in the URL
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
and this can be manipulated at the backend like this
$urls = $_GET['ID'];
foreach($urls as $url){
echo $url;
}
OR
An alternative would be to pass json encoded arrays
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=[1,2,24,32]
which can be used as
$myarr = json_decode($_GET['ID']); // array(1,2,24,32)
I recommend you to also see for this here.
http_build_query()
it's wrong but if you really want to do this
<?php
function getIds($string){
$string = preg_match_all("/[ID]+[=]+[0-9]/i", $string, $matches);
$ids = [];
foreach($matches[0] as $match)
{
$c = explode("=", $match);
$ids [] = $c[1];
}
return $ids;
}
// you can change this with $_SERVER['QUERY_STRING']
$url = "http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32";
$ids = getIds($url);
var_dump($ids);

PHP break string into two parts

Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 12);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$string = 'The Best Hotel Ever';
$exp = explode(' ', $string);
if (strlen($exp[0]) < 12) {
$tmp = $exp[0];
$i = 1;
while (strlen($tmp . ' ' . $exp[$i]) < 12) {
$tmp .= " " . $exp[$i];
$i++;
}
$array[0] = $tmp;
while (isset($exp[$i])) {
$array[1] .= ' ' . $exp[$i];
$i++;
}
$array[1] = trim($array[1]);
} else {
$array[0] = '';
$array[1] = trim(implode (' ', $exp));
}
var_dump($array);
// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" }
// $string1 = 'The';
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" }
// $string2 = 'Thebesthotelever';
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 8);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
For further help check out because you need to remember to count from zero up:
http://php.net/manual/en/function.substr.php

How to remove or trim special characters (\n) from Array?

I have created a Array and are not able to echo values from it. Below I have copy pasted source code results from my browser. As you can see "]=> starts on new line. How can I solve this
using this function:
function remap_alternating(array $values) {
$remapped = array();
for($i = 0; $i < count($values) - 1; $i += 2) {
$remapped[strip_tags(trim($values[$i], " "))] = strip_tags(trim($values[$i + 1], " "));
}
return $remapped;
}
$mapped = remap_alternating($matches[0]);
$keys = str_replace( ':', '', array_keys($mapped) );
$values = array_values($mapped);
$mapped = array_combine($keys, $values);
Result of var_dump($mapped); (Copy Paste from Browser Source Code)
array(32) {
["Age
"]=>
string(9) "21 Yrs.
"
["Ethnicity
"]=>
string(6) "Black
"
["Location
"]=>
string(36) "Dubai, Dubayy, United Arab Emirates
"
My question is how I can get echo $mapped[Age];to work?
Thank you
You can specify the characters to trim in the second argument of trim(): http://us2.php.net/trim
You look to be specifying only " ", in the trim() function you're using. Leave the second argument blank so it will trim the default characters which includes \n.

Categories