Always getting last value of array - php

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

Related

Laravel, how to change array key permanently?

Tried using array_values but it only temporary.
controller
foreach($rows as $key => $value)
{
array_values($value);
//dd shows the key changes to [0], [1], [2] and so on
}
You can do it like this,
$rows = array_map(function($v){return array_values($v);}, $rows);
Something like this should work:
$new = [];
foreach($rows as $key => $value)
{
array_values($value);
$sub = [];
foreach ($value as $subKey => $subValue) {
$subKey = $key;
$sub[$key] = $subValue;
}
$new[$key] = $sub;
//dd shows the key changes to [0], [1], [2] and so on
}
Then return $new instead of $rows.
Since you're using laravel you can also do:
$rows = collect($rows)->map(function ($value) {
return Arr::accessible($value)?collect($value)->values()->all():$value;
})->all();
If you are trying to change the associative array to an indexed array, do this:
$array = array_values($array);

How to "skip" iteration when building a new array using recursion

I am stuck on something that might be very simple.
I am creating a new array by looping through an existing array using a recursion function yet I can not seem to get the values to stick to the new array. The function, in the end, will be a bit more complex, but for now I need some help.
I have tried soooo many ways to get this to work but I am at a loss right now.
Here is my php function
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
As is, the new array never gets filled...BUT, if I change this line...
recursive($value); // Why can't I just call the recursive function here?
...to...
$newArray[] = recursive($value); // Instead of having to set a new value to the new array?
everything works properly...except that my goal was to create a flat array with only the values.
So my question is, why is it necessary to set a new array value in order to call the recursive function again? Ideally, I want to skip setting a new array value if the value is an array and just continue the loop through the original array.
Use array_merge:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or you could use special operator:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray += recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or pass a variable by reference like this:
function recursive($array, &$newArray = null) {
if (!$newArray) {
$newArray = array();
}
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value, $newArray);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
use array_merge() to merge the array returned from recursive($value); and $newArray
$newArray = array_merge($newArray,recursive($value));
You can guarantee that $newArray will be flat after this, as the previous value of $newArray was flat, and recursive always returns a flat array, so the combination of both should be a flat array.
You aren't doing anything with the return from your recursive function. Try this:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
// This is what was modified
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}

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

change the first letter of value of an array to uppercase

$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);

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.

Categories