I have a template system, that replaces text such as {HEADER} with the appropriate content. I use an array like this, that replaces the key with the value using str_replace.
$array = array("HEADER","This is the header");
foreach($array as $var => $content) {
$template = str_replace("{" . strtoupper($var). "}", $content,$template);
}
Now im trying to use a defined variable like this:
define("NAME","Site Name");
Inside the value for the header. So I want the defined variable to be inside the array which gets replaced so it would look like this, but it doesn't work.
$array = array("HEADER","Welcome to ".NAME."'s website!");
Any ideas? tell me if im not clear
Shouldn't your array line be:
$array = array("HEADER" => "Welcome to ".NAME."'s website!");
Since you are accessing the array items by key and value?
The way you are looping through the array, using :
foreach($array as $var => $content) {
// ...
}
makes me think you should use an associative array for your $array.
i.e., it should be declared this way :
$array = array("HEADER" => "Welcome to ".NAME."'s website!");
And, as a demonstration, here's an example of code :
$template = <<<TPL
Hello, World !
{HEADER}
And here's the content ;-)
TPL;
define("NAME","Site Name");
$array = array("HEADER" => "Welcome to ".NAME."'s website!");
foreach($array as $var => $content) {
$template = str_replace("{" . strtoupper($var). "}", $content,$template);
}
var_dump($template);
And the output I get it :
string 'Hello, World !
Welcome to Site Name's website!
And here's the content ;-)' (length=73)
Which indicates it's working ;-)
(It wasn't, when $array was declared the way you set it)
When using this :
$array = array("HEADER","This is the header");
var_dump($array);
You are declaring an array that contains two items :
array
0 => string 'HEADER' (length=6)
1 => string 'This is the header' (length=18)
On the other hand, when using this :
$array = array("HEADER" => "This is the header");
var_dump($array);
You are declaring an array that :
contains only one item
"HEADER" being the key
and "This is the header" being the value
Which gives :
array
'HEADER' => string 'This is the header' (length=18)
When using foreach ($array as $key => $value), you need the second one ;-)
And, purely for reference, you can take a look at, in the manual, the following pages :
Arrays
foreach
Related
I have an array in PHP defined as:
$myArray = array(
"key_1" => "value_1",
"key_2"=> value_2",
"key_3"=> value_1",
)
Is there a function that could print it as:
[{key_1=value_1, key_2=value_2, key_3=value_3}] ?
I know Java provides Arrays.asList(myHashMap) for doing this for hashmaps (which are associative arrays like PHP)
Is there a function in PHP that's equivalent to Arrays.asList(val) in Java?
I don't know any array method that does this.
One way:
foreach($myArray as $key => $value) {
echo "$key=$value ";
}
Another one (each is deprecated as of php 7.2):
print_r(each($myArray));
Another dirty way you could achieve this is with the following
$array = array(
"key_1" => "value_1",
"key_2" => "value_2",
"key_3" => "value_1",
);
echo str_replace('"', '', str_replace(':', '=', json_encode([$array])));
if you want to print the content of an array with the keys, you can use the print_r($array) or $return = print_r($array,1), to have the string assigned to $return variable.
I have a function that returns an multidimensional array() I want to concatenate a string to every value of that array. How can I do this
for example my string:
$this->$string = 'helloAddMeToArray';
and my array is:
array(array('url' => 'PleaseAddAStringToMeIAmLonely'));
So i need my array value to be like this: helloAddMeToArrayPleaseAddAStringToMeIAmLonely
I tried concatenating these with '.' but does not allow me
$oldArray = array(array('url' => 'PleaseAddAStringToMeIAmLonely'));
$newArray = array();
$this->string = 'helloAddMeToArray';
foreach($oldArray as $o) {
$newArray[] = array('url' => $this->string . $o['url']);
}
Try this:
First get string from your multidimentional Array, and type cast it.
$myString2 = (string)$myArray[0]->url;
Now use concatination: $string.$myString2;
Assuming your array could look like :
[
"key"=>[
"keyK"=>"val"
],
"key2"=>"val2"
]
and you want to concatenate a string to every value from that array you should use array_walk_recursive function .
This is a short snnipet doing this job :
$stringToConcatenate=$this->$string = 'helloAddMeToArray';
$callback($val,$key) use ($stringToConcatenate){
$val.=$val.$stringToConcatenate;
}
array_walk_recursive($youArray,$callback);
I hope it helps you .
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
I have a multidimensional array, e.g.:
$values = array(
'one' => array(
'title' => 'Title One',
'uri' => 'http://example.com/one',
),
'two' => array(
'title' => 'Title Two',
'uri' => 'http://example.com/two',
),
);
...and I'd like to parse through that with a closure in my implode function, à la:
$final_string = implode(' | ', function($values) {
$return = array();
foreach($values as $value)
$return[] = '' . $value['title'] . '';
return $return;
});
However, this usage yields an Invalid arguments passed error. Is there syntax that I'm missing which will make this use of closures possible? I'm using PHP v5.3.16.
Use array_map:
$final_string = implode(' | ', array_map(function($item) {
return '' . $item['title'] . '';
}, $values));
I trust you'll properly escape the values as HTML in your real code.
As to why this works and your code doesn't, you were passing a function as the second argument to implode. Frankly, that makes little sense: you can join a bunch of strings together, or maybe even a bunch of functions, but you can't join a single function together. It sounds strange, especially if you word it that way.
Instead, we first want to transform all of the items in an array using a function and pass the result of that into implode. This operation is most commonly called map. Luckily, PHP provides this function as, well, array_map. After we've transformed the items in the array, we can join the results.
It seems that you need to assign the function to a variable, and then pass it through to make it work.
$fn = function($values) {
$return = array();
foreach($values as $value)
$return[] = '' . $value['title'] . '';
return $return;
};
$final_string(' | ', $fn($values));
echo $final_string;
I am not sure what the reason is, though, and will need to check it in a little more depth to be able to give you a proper reason.
You can see the code working here
EDIT : Converted this answer to a community wiki so that everyone can contribute here.
EDIT : Explanation by #kmfk
When you pass the closure directly to the implode method - which explicitly wants a second argument of type array, it essentially checks the instanceof - hence the invalid argument. The implode function does not expect mixed type and doesn't know to execute the closure to get an array.
When you first assign that function to a variable, it causes PHP to first evaluate that variable and it ends up passing the returned value from the function into implode.
In that case you're returning an array from the function and passing that into implode - that checks out.
That anonymous function would be instanceof Closure, and
Closure !== array
Ashwin's answer is correct. Here's why:
When you pass the closure directly to the implode method - which explicitly wants a second argument of type array, it essentially checks the instanceof - hence the invalid argument. The implode function does not expect mixed and doesn't know to execute the closure.
When you first assign that function to a variable, it causes PHP to first evaluate that variable and it ends up passing the returned value from the function into implode.
In that case you're returning an array from the function and passing that into implode - that checks out.
edit/adding: that anonymous function would be instanceof Closure.
Closure !== array
You can't use implode to what your trying to achieve, because implode only accept an array as the second argument.
You can try something like this.
$values = array(
'one' => array(
'title' => 'Title One',
'uri' => 'http://example.com/one',
),
'two' => array(
'title' => 'Title Two',
'uri' => 'http://example.com/two',
),
);
$links = array();
foreach ($values as $value) {
$links[] = "<a href='" . $value['uri'] . "'>" . $value['title'] . "</a>";
}
$string = implode(" | ", $links);
function implode_callback( $array, $separator = '', $callback = false )
{
return implode(
$separator,
$callback === false ?
$array : array_map( $callback, $array )
);
}
Example use:
$tab = array( 1, 2, 3 );
echo implode_callback( $tab, '<hr>', function($x) { return "<p>$x</p>"; } );
See example code
So i have a problem with taking an array and looping through the values and outputing with a foreach statement.
code
<?php
$example = array("test" => "hello world" );
foreach ($example as $arr) {
printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$arr["test"]);
}
?>
hoping to get the output:
what do you have to say for yourself?
hello world!
Instead get
what do you have to say for yourself?
h!
why just the single character?
Any help would be great
thanks
Your foreach loop is already going through the values of the array, so don't reference the value again using the key:
<?php
$example = array("test" => "hello world" );
foreach ($example as $key => $val) {
printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$val);
}
?>
From your other example in the comments, you would not be able to use a loop because the placements are very specific. Instead reference each value specifically without a loop:
$example = array(
"first" => "Bob",
"last" => "Smith",
"address" => "123 Spruce st"
);
printf("<p>my name is %s %s and i live at %s</p>",
$example['first'],
$example['last'],
$example['address']
);
Perhaps looking at it this way will help;
<?php
$example = array("test" => "hello world", "foo" => "bar");
foreach ($example as $key => $val) {
# option 1
echo "<p>what do you have to say for yourself?</p><p>$key => $val</p>";
# option 2
echo "<p>what do you have to say for yourself?</p><p>$key => $example[$key]</p>";
}
?>
Once you see how it iterates through, you can put your statement back into printf() or do whatever with the variables.
Note that if you have multidimensional arrays, you can refer to the next level of the array by addressing the key;
Looping over your associative array is putting a value in $arr each iteration. When you try to index into $arr you're actually indexing into a string, hence the single character.
Foreach assumes there is more than one element in the array. If not just echo out the element like echo $example['test']; No need for a looping construct. If more than one element:
$example = array('text'=>"what do you have to say for yourself?",'test' => "hello world" );
print_r($example);
foreach ($example as $value)
printf("<p>%s!</p>",$value);
foreach is assigning the value of an array element to a variable called $value on each loop. Make sense?