change the first letter of value of an array to uppercase - php

$arr = array ('name'=>'bunt','game'=>'battlefield','fame'=>'hero');
foreach ($arr as $key=>$val){
$val = ucfirst($val);
}
var_dump($arr);
// result would be
// 'name' => 'Bunt', 'game' => 'Battlefield', 'fame' => 'Hero'
I am missing something here.... How to accomplish this ?

Use array_map()
$new_array = array_map('ucfirst', $arr);
See it in action

$val is just a temporary variable in each iteration. To update the value of each key you need to pass it as a reference. Do this.
foreach ($arr as $key => &$val) {
$val = ucfirst($val);
}
Notice the & following $val.
Here's some documentation on references in PHP.

foreach ($arr as $key=>&$val){
$val = ucfirst($val);
}
Put an & sign before $val . that will make it reference the variable instead of assigning the value.

Why not just use the key to access the array?
<?php
$arr = array('name' => 'bunt', 'game' => 'battlefield');
foreach ($arr as $key => $val) {
$arr[$key] = ucfirst($val);
}
var_dump($arr);

Related

Always getting last value of array

Why am I getting always the last value from the array? I'm stuck on what I'm doing wrong.
Please help! :p
$array = array("id"=>"4", "id"=>"5", "id"=>"6");
foreach($array as $key => $value) {
$screenshots[] = $value;
}
var_dump($screenshots);
As Rizier said, your keys in an associative array cannot have the same name.
This should work:
$array = array("id1"=>"4", "id2"=>"5", "id3"=>"6");
foreach($array as $key => $value) {
$screenshots[] = $value;
}
var_dump($screenshots);

Get keys of an array where values is not NULL in PHP

I have an associative array in PHP
$a = array("d1" => "data", "d2" => NULL, "d3" => "data")
I want to get all keys and all values which are not NULL, in order to implode them:
// e.g.:
$sub_key = array_keys($a, keys != NULL);
$sub_values = array_values($a, values != NULL);
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'";
Are there functions like array_keys() and array_values() that allow to take only vales that do not match the pattern?
Use array_filter before using array_keys and filter the array like this
$newArray = array_filter($a);
Then do
$sub_key = array_keys($newArray);
$sub_values = array_values($newArray);
You could use array_filter($a), but as one of the comments above pointed out, this would also filter out values like FALSE, empty strings, etc. So I'd use a foreach loop.
$new_array = array();
foreach ($a as $key => $value) {
if (is_null($value) === false) {
$new_array[$key] = $value;
}
}
Please try this:
// Loop to find empty elements and
// unset the empty elements
foreach($array as $key => $value)
if(empty($value))
unset($array[$key]);
// Display the array elements
foreach($array as $key => $value)
echo ($array[$key] . "<br>");
In you case you will replace $array with $a. This will work for null/empty key values.
$a = array("d1" => "data1", "d2" => NULL, "d3" => "data3");
$b = array_filter($a); // Not Null Values Array
$sub_key = array_keys(array_filter($a));
$sub_values = array_values(array_filter($a));
echo "`".implode("`,`", $sub_key)."` <br/>";
echo "'".implode("','", $sub_values)."'";
$sub_key = array();
$sub_values = array();
foreach ($a as $key => $value) {
if (!is_null($key) && !is_null($value)) { // you can also do is_empty() in stead of is_null() if you also wan't to avoid empty string
$sub_key[] = $key;
$sub_values[] = $value; // or use mysql_real_escape_string($value) if you are going to create a query with this! Otherwise you will create an SQL injection vulnerability here.
}
}
// you can add if(count($sub_key)) here to only do the echoes, if there was at least 1 item in the array. Otherwise you will echo an empty ``
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'"; // don't you mean $sub_values here?

How to change first char of each key in array?

I have an array with all keys in lover case and i need to change them that the firs char would be in uppercase, like ucfirs function does. Is it possible without creating a new array?
It's not possible without creating a new array, but here's a funky one-liner you could use:
$array = array_combine(
array_map('ucfirst', array_keys($array)),
array_values($array)
);
It breaks up the array into keys and values, transforms the keys and then glues the two pieces back together.
Try this code:
foreach ($array as $key => $value) {
unset ($array[$key]);
$array[ucfirst($key)] = $value;
}
try this
foreach ($arr as $key=>$val){
unset($arr[$key]);
$key = ucfirst($key);
$arr[$key]=$val;
}
try this. it will work for nested array too.
<?php
function ucfirstKeys(&$data)
{
foreach ($data as $key => $value)
{
// Convert key
$newKey = ucfirst($key);
// Change key if needed
if ($newKey != $key)
{
unset($data[$key]);
$data[$newKey] = $value;
}
// Handle nested arrays
if (is_array($value))
{
ucfirstKeys($data[$key]);
}
}
}
$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo'));
ucfirstKeys($test);
print_r($test);

Changing value inside foreach loop doesn't change value in the array being iterated over

Why does this yield this:
foreach( $store as $key => $value){
$value = $value.".txt.gz";
}
unset($value);
print_r ($store);
Array
(
[1] => 101Phones - Product Catalog TXT
[2] => 1-800-FLORALS - Product Catalog 1
)
I am trying to get 101Phones - Product Catalog TXT.txt.gz
Thoughts on whats going on?
EDIT: Alright I found the solution...my variables in my array had values I couldn't see...doing
$output = preg_replace('/[^(\x20-\x7F)]*/','', $output);
echo($output);
Cleaned it up and made it work properly
The doc http://php.net/manual/en/control-structures.foreach.php clearly states why you have a problem:
"In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:
<?php
/** this won't work **/
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
Try
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
The $value variable in the array is temporary, it does not refer to the entry in the array.
If you want to change the original array entry, use a reference:
foreach ($store as $key => &$value) {
// ^ reference
$value .= '.txt.gz';
}
You are rewriting the value within the loop, and not the key reference in your array.
Try
$store[$key] = $value.".txt.gz";
pass $value as a reference:
foreach( $store as $key => &$value){
$value = $value.".txt.gz";
}
Try
$catalog = array();
foreach( $store as $key => $value){
$catalog[] = $value.".txt.gz";
}
print_r ($catalog);
OR
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
print_r ($store);
Depends on what you want to achieve
Thanks
:)
I believe this is what you want to do:
foreach( $store as $key => $value){
$store[$key] = $value.".txt.gz";
}
unset($value);
print_r ($store);
How about array map:
$func = function($value) { return $value . ".txt.gz"; };
print_r(array_map($func, $store));
foreach(array_container as & array_value)
Is the way to modify array element value inside foreach loop.

i want to use iconv function for array?

this is my array:
$array = array(
'name' => $burcname . ' Günlük yorumum',
'link' => 'http://apps.facebook.com/gunlukburcpaylas/sonuc.php?burc='. $burc,
'description' => $burcname . ' Günlük yorumu. Sizde her gün profilinizde günlük burç yorumunuz için uygulamaya katılın..',
'message' => $aciklama,
'picture' => $picture
);
iconv as: $example = iconv('UTF-8','ISO-8859-9',$array);
But this is array. and dont work. What can i do?
You will need to iterate the array contents, or use a function like array_walk.
Foreach loop (untested)
foreach(array_keys($array) as $key){
$array[$key] = iconv('UTF-8','ISO-8859-9', $array[$key]);
}
The reason you need to use array_keys in this example is because a standard foreach loop with foreach($array as $key => $value) or foreach($array as $value) modifications made to $value are not preserved.
Using array_walk (untested)
function convert(&$value, $key){
$value = iconv('UTF-8','ISO-8859-9', $value);
}
array_walk($array, 'convert');
If you are using PHP > 5.3 then you can use a lambda function instead.
array_walk_deep function (tested)
$array = array("a",
array("b",
array("c",
"d"
)
)
);
function array_walk_deep(&$items,$func){
foreach ($items as &$item) {
if(is_array($item))
array_walk_deep($item,$func);
else
$item = $func($item);
}
}
array_walk_deep($array, 'strtoupper');
print_r($array);
Another solution would be to return the results from the foreach by reference instead of by value:
foreach( $array as &$value ) {
$value = iconv( 'UTF-8','ISO-8859-9', $value );
}
The '&' in front of the value variable lets you use the actual array value instead of a copy. :)

Categories