using extract in php to print array value - php

I'm using extract passing it an associative array $arr but it doesn't work properly. I pass the array to my function extract($arr) but when I want to extract value it doesn't work. how can use it correctly?
here my array:
$arr = array('id' => 1, 'name' => 'abc','address' => 'street abc');

If you're using it like this it should work.
<?php
$arr = array('id' => 1, 'name' => 'abc','address' => 'street abc');
extract($arr);
echo $id . "\n";
echo $name . "\n";
echo $address;
?>
Output:
1
abc
street abc
This code shows the output fine. Post your exact code so that we can reproduce the problem.

Related

How to get a string from requested array PHP

I have a file swifts.php with code (I have written this after a lot of research)
<?php
$swift= array(
'PBANUA2XXXX' => 'PRIVATBANK',
'Swift2' => 'word2',
'Swift3' => 'word3',
'Swift4' => 'word4',
'Swift5' => 'word5',
'etc' => 'word6',
'etc..' => 'word7',
);
echo http_build_query($swift) . "\n";
echo http_build_query($swift, '', '&');
?>
My question is how to receive a string for example when I request the Swift3 with https://example.com/swifts.php?swift=Swift3
I want to receive in a page just the string word3 but it shows me all the arrays like: PBANUA2XXXX=PRIVATBANK&Swift2=word2&Swift3=word3& etc etc....
How I can get what I request?
You have to get query string by using $_GET.
Then use your array to get value
echo $swift[$_GET['swift']]; // as $_GET['swift'] = Swift3
so $swift[$_GET['swift']] = 'word3';

Adding String to String in an array in php

I am using a database to get the prices as displayed as "Betrag". The actual value of "Betrag" is "18981", but i am converting it by:
$tabledata[] = array('category' => $beschriftung, 'value' => number_format($zeile['summe'], 0, ',', '.').'€', 'id' => $i);
My problem is that i want to get the marked text "Anzahl: 413" below the price, but using the number_format, it doesn't work. I was trying something like $tabledata += or just adding it after the conversion but it didn't get my expected output. It all works with a while loop iterating over the id.
So the actual question is:
Is it possible to add a String to an array without deleting the value which is alredy in it?
Feel free to ask questions or give comments.
Thats the wrong place to fix your "issue". $tabledata is only an array, printed somewhere else and at this point, you have to move the output of your "Betrag". That means of couse, you have to add it to your $tabledata array.
$tabledata[] = array(
'category' => $beschriftung,
'value' => number_format($zeile['summe'], 0, ',', '.').'€',
'id' => $i,
'count' => $betrag
);
and later, you have to print it right after $value. (Something like this..)
foreach ($tabledata as $row) {
// ...
echo $row['value'];
echo "<br />";
echo "Anzahl:" . $row['count'];
// ...
}
But thats only an example and depends on how you build your response (maybe inside an template engine, ...)
Of couse, you could also do the fast and bad way by just append the "Betrag" to the value with a <br /> delimeter.
$tabledata[] = array(
'category' => $beschriftung,
'value' => number_format($zeile['summe'], 0, ',', '.').'€' . '<br />Anzahl: ' . $betrag,
'id' => $i
);
it is possible to add a string to a value which already is in an array - for example
<?php $einArray = array('text1','text2');
$einArray[1] .= "test";
echo $einArray[1];
?>
Will output "text2test".
Is this the answer to your problem?

PHP MySQL Assign variables to array data

I have the following:
$sql="SELECT course_status, COUNT(course_name) FROM courses GROUP BY course_status";
Then a while loop to store the data:
$menu[] = array(
'sum_status' => $row['COUNT(course_name)'],
'course_status' => $row['course_status']
);
I can print_r($menu) with all data.
How can I assign the keys and values to different variables like:
$status_0 = $key[0] <br>
$count_0 = $value[0] <br>
$status_1 = $key[1] <br>
$count_1 = $value[1] <br>
and so on...?
Thank you!
A little more info, perhaps pasting the code, would be helpful. If I understand it correctly, you could just change your query to:
$sql="SELECT course_status as 'status', COUNT(course_name) as 'count' FROM courses GROUP BY course_status";
Then a simple foreach loop will give you the right display.
I am not entirely understanding your question. But iterating through an array of arrays is a simple as:
<?php
$items = [
[
'foo' => 'Hello',
'bar' => 23
],
[
'foo' => 'Earth',
'bar' => 47
]
];
foreach($items as $item) {
echo $item['foo'];
echo $item['bar'];
}
Output:
Hello23Earth47
Further, rather than assigning to individual variables, you can access an individual item's value by targeting the appropriate key:
echo $items[1]['foo'];
Output:
Earth
To parse the array item in a string, wrap with curlies:
echo "{$items[0]['foo']} Dolly";
Output:
Hello Dolly

json_decode returns NULL on a json_encod-ed string

I have this bit of code:
<?php $arr= array(
array
(
'name' => 'Sony PS4',
'quantity' => '1',
'unit_price' => '$250.00'
),
array
(
'name' => 'XBox 360',
'quantity' => '1',
'unit_price' => '$200.00'
));?>
Then I have this Ajax-request line
<?php $encoded_json = json_encode($arr); echo '<script>'; echo 'var encodedStr = "'. $encoded_json. '"'; echo 'var params = "encodedValue=" + encodedStr'; //Ajax GET request with 'params' variable goes here, </script>';?>
And here's the ajax-request-processing line:
<?php $encoded_value = $_GET['encodedValue']; json_decode($encoded_value); //this gives me null, rather than the original encoded array ?>
Is there something not right with my code? How do I get back my original array? Any pointers in the right direction, please.
Firstly, you need to send the JSON as a string to PHP. There are plenty of ways of doing this like JSON.stringify.
Then you should check if there is an actual JSON formatted string to decode.
Then check what value is returned from the json_decode function, if the value is not true, then check the error with json_last_error function
$encoded_value = $_GET['encodedValue'];
if (!$encoded_value) { die('No value to parse'); }
$result = json_decode($encoded_value);
if (!$result) { die(json_last_error()); }

getting each value of an associative array

i need help building a function that display an associative array and i want to insert them in a variable. for example i have this assoc array :
$array[ID] = 1;
$array[Name] = John;
$array[age] = 12;
$array[ID]=2;
$array[Name] = Mary;
$array[age] = 14;
i need to make the ID,name,age as variables so i can display it in a table. when i loop through them each time it fills the table row. it has to be each one a variable coz i need to insert them into a gird and display the grid .. where then i can update delete the info
I'd use one of the answers provided but if you really really want to (again, i don't see a reason but what the hell do i know) use extract()
<?php
$people = array(
array('id' => 1, 'name' => 'John', 'age' => 12),
array('id' => 2, 'name' => 'Mary', 'age' => 14)
);
foreach($people as $row) {
extract($row);
echo "Id: $id, Name: $name, Age: $age\n";
}
//Prints:
//Id: 1, Name: John, Age: 12
//Id: 2, Name: Mary, Age: 14
~
Currently it looks as if you are overwriting the values of the first person with the values of the second person.
What you're looking for is an array structure with more than one dimension, like this:
$people = array(
1 => array('name' => 'John', 'age' => 12),
2 => array('name' => 'Mary', 'age' => 14)
);
Then it'll be easy to print out table rows:
foreach($people as $id => $person){
print '<tr><td>'.$id.'</td><td>'.$person['name'].'</td><td>'.$person['age'].'</td></tr>';
}//foreach
Hope this helps!
foreach($array as $row) {
echo $row['ID'],$row['Name'],$row['age'];
}
Im not sure what you want to do exactly, but maybe it is the extract function you are looking for.
foreach($array as $key => $value){
echo $key. ' = '.$value.";
}
would give you
ID = 1
Name = John
age = 12
etc
Also be sure to do $array["ID"] = ... instead of $array[ID] = ...
You can do:
foreach($array as $user) {
list($age, $name, $id) = array_values($user);
echo $id, $name, $age;
}
But like others already pointed out, this is pointless because you can much more easily read the values directly from the array through their associative keys. You also wouldnt have to run array_values to assign the array values before being able to assign them with list.

Categories