printf issue with array - php

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?

Related

PHP: How to extract this string

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;
}
}

How to make sure the value is reset in a 'foreach' loop in PHP?

I was writing a simple PHP page and a few foreach loops were used.
Here are the scripts:
$arrs = array("a", "b", "c");
foreach ($arrs as $arr) {
if(substr($arr,0,1)=="b") {
echo "This is b";
}
} // End of first 'foreach' loop, and I didn't use 'ifelse' here.
And when this foreach ends, I wrote another foreach loop in which all the values in the foreach loop was the same as in the previous foreach.
foreach ($arrs as $arr) {
if(substr($arr,0,1)=="c") {
echo "This is c";
}
}
I am not sure if it is a good practice to have two foreach loops with the same values and keys.
Will the values get overwritten in the first foreach loop?
It's OK until you start using references and then you can get strange behaviour, for example:
<?php
$array = array(1,2,3,4);
//notice reference &
foreach ($array as & $item) { }
$array2 = array(10, 11, 12, 13);
foreach ($array2 as $item) { }
print_r($array);
Outputs this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 13
)
Because the first foreach leaves $item as a reference to $array[3], $array[3] is sequentially set to each value in $array2.
You can solve this be doing unset($item) after the first foreach, which will remove the reference, but this isn't actually an issue in your case, as you are not using references with foreach.
Two notable notes from the documentation of foreach:
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
and
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
Because you're not writing to the array, only reading from it and printing stuff out, no values in the array will be changed.
You can save time looping through the array twice though by doing this:
$arrs = array("a", "b", "c");
foreach ($arrs as $arr) {
if(substr($arr,0,1)=="b") {
echo "This is b";
}
if(substr($arr,0,1)=="c") {
echo "This is c";
}
}
All you need is 1 foreach loop.
Or an even shorter approach to what Jon said, is this:
$arrs = array("a", "b", "c");
foreach ($arrs as $arr)
if ($arr != "a")
echo 'This is ' . $arr;
This is much easier and faster than using substr, since you are already using a foreach loop. And try not to pollute it with a ton of if statements, if you find yourself doing this, it's better to use a switch statement, much faster.
Cheers :)

php define variable inside str_replace array

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

Array - How do I access value at specified key, without using $array['key'] method?

For example:
$fruits = array(
1 => 'apples',
2 => 'lemons',
3 => 'bananas'
);
Is there a function to output lemons, without using $fruits[2]?
You could use next(), current(), prev(), end() set of functions. You could use a foreach on the array. You could use the list($var,$var1,$var2...) = $arr construct. Be more specific as to what you're trying to do.
EDIT:
If you're looking for a way to echo it in text use
$foo='LEMON: '.$fruits[2].' =)';
OR
$foo=:LEMON: {$fruits[2]} =)";
foreach($fruits as $k => $v) if ($k===2) echo $v;
list($f1,$f2,$f3) = $fruits;
echo $f2;
next($fruits);
echo next($fruits);
array_shift($fruits);
echo $array_shift($fruits);
array_shift():
echo array_shift($fruits);
But it works only with the first element in the array of course ;)

Assigning an array element to a variable with the same name?

I'd like to be able to extract some array elements, assign each of them to a variable and then unset these elements in the array.
Let's say I have
$myarray = array ( "one" => "eins", "two" => "zwei" , "three" => "drei") ;
I want a function suck("one",$myarray)as a result the same as if I did manually:
$one = "eins" ;
unset($myarray["one"]) ;
(I want to be able to use this function in a loop over another array that contains the names of the elements to be removed, $removethese = array("one","three") )
function suck($x, $arr) {
$x = $arr[$x] ;
unset($arr[$x]) ;
}
but this doesn't work. I think I have two prolbems -- how to say "$x" as the variable to be assigned to, and of function scope. In any case, if I do
suck("two",$myarray) ;
$two is not created and $myarray is unchanged.
Try this:
$myarray = array("one" => "eins", "two" => "zwei" , "three" => "drei");
suck('two', $myarray);
print_r($myarray);
echo $two;
function suck($x, &$arr) {
global $$x;
$$x = $arr[$x];
unset($arr[$x]);
}
Output:
Array
(
[one] => eins
[three] => drei
)
zwei
I'd build an new array with only the key => value pairs you want, and then toss it at extract().
You can do
function suck($x, $arr) {
$$x = $arr[$x] ;
unset($arr[$x]) ;
}
, using variable variables. This will only set the new variable inside the scope of "suck()".
You can also have a look at extract()
Why not this:
foreach ($myarray as $var => $val) {
$$var = $val;
unset($myarray[$var]);
echo "$var => ".$$var . "\n";
}
Output
one => eins
two => zwei
three => drei
If I've understood the question, you have two problems
The first is that you're setting the value of $x to be the value in the key-value pair. Then you're unsetting a key that doesn't exist. Finally, you're not returning anything. Here's what I mean:
Given the single element array $arr= array("one" => "eins") and your function suck() this is what happens:
First you call suck("one", $arr). The value of $x is then changed to "eins" in the line $x=$arr[$x]. Then you try to unset $x (which is invalid because you don't have an array entry with the key "eins"
You should do this:
function suck($x, $arr)
{
$tmp = $arr[$x];
unset($arr[$x]);
return $tmp
}
Then you can call this function to get the values (and remove the pair from the array) however you want. Example:
<?php
/* gets odd numbers in german from
$translateArray = array("one"=>"eins", "two"=>"zwei", "three"=>"drei");
$oddArray = array();
$oddArray[] = suck($translateArray,"one");
$oddArray[] = suck($translateArray, "three");
?>
The result of this is the array called translate array being an array with elements("eins","drei");
HTH
JB

Categories